Constructor overloading in java

Constructor overloading:

  • If one class has more than one constructor different parameters list called Constructor overloading.

Example program:

  1. class StudentData

    {

       private int stuID;

       private String stuName;

       private int stuAge;

       StudentData()

       {

           //Default constructor

           stuID = 1001;

           stuName = "Sabrina";

           stuAge = 15;

       }

       StudentData(int num1, String str, int num2)

       {

           //Parameterized constructor

           stuID = num1;

           stuName = str;

           stuAge = num2;

       }

     

       public int getStuID() {

           return stuID;

       }

       public void setStuID(int stuID) {

           this.stuID = stuID;

       }

       public String getStuName() {

           return stuName;

       }

       public void setStuName(String stuName) {

           this.stuName = stuName;

       }

       public int getStuAge() {

           return stuAge;

       }

       public void setStuAge(int stuAge) {

           this.stuAge = stuAge;

       }

     

       public static void main(String args[])

       {

           //This object creation would call the default constructor

           StudentData obj = new StudentData();

           System.out.println("Values from Default constructor.....");

           System.out.println("Student Name is: "+obj.getStuName());

           System.out.println("Student Age is: "+obj.getStuAge());

           System.out.println("Student ID is: "+obj.getStuID());

     

           System.out.println("\nValues from Parameterized constructor.....");

           StudentData obj2 = new StudentData(2005, "Kurshitha", 18);

           System.out.println("Student Name is: "+obj2.getStuName());

           System.out.println("Student Age is: "+obj2.getStuAge());

           System.out.println("Student ID is: "+obj2.getStuID());

      }

    }

Output:

Note:

If you need details about this keyword then click the below link to detail learning.

https://www.whereisstuff.com/2020/11/use-of-this-keyword-in-java.html

Share:

1 comment:

Recent Posts

Service Support

Need our help to Learn or Post New Concepts Contact me