1class StudentData
2{
3 private int stuID;
4 private String stuName;
5 private int stuAge;
6 StudentData()
7 {
8 //Default constructor
9 stuID = 100;
10 stuName = "New Student";
11 stuAge = 18;
12 }
13 StudentData(int num1, String str, int num2)
14 {
15 //Parameterized constructor
16 stuID = num1;
17 stuName = str;
18 stuAge = num2;
19 }
20 //Getter and setter methods
21 public int getStuID() {
22 return stuID;
23 }
24 public void setStuID(int stuID) {
25 this.stuID = stuID;
26 }
27 public String getStuName() {
28 return stuName;
29 }
30 public void setStuName(String stuName) {
31 this.stuName = stuName;
32 }
33 public int getStuAge() {
34 return stuAge;
35 }
36 public void setStuAge(int stuAge) {
37 this.stuAge = stuAge;
38 }
39
40 public static void main(String args[])
41 {
42 //This object creation would call the default constructor
43 StudentData myobj = new StudentData();
44 System.out.println("Student Name is: "+myobj.getStuName());
45 System.out.println("Student Age is: "+myobj.getStuAge());
46 System.out.println("Student ID is: "+myobj.getStuID());
47
48 /*This object creation would call the parameterized
49 * constructor StudentData(int, String, int)*/
50 StudentData myobj2 = new StudentData(555, "Chaitanya", 25);
51 System.out.println("Student Name is: "+myobj2.getStuName());
52 System.out.println("Student Age is: "+myobj2.getStuAge());
53 System.out.println("Student ID is: "+myobj2.getStuID());
54 }
55}
1Yes, the constructors can be overloaded by changing the number of
2arguments accepted by the constructor or by changing the data type of
3the parameters
1Default constructor is a constructor created by compiler; if user does not
2create a constructor in a class.
3If user defines a constructor in a class then java compiler will not create
4default constructor.
1class Student{
2 private String stuname;
3 private String stuid;
4 private int stuage;
5
6 Student(){
7 System.out.println("this a default constructor");
8
9 }
10 Student(String stuname,String stuid,int stuage){
11 this.stuname=stuname;
12 this.stuid=stuid;
13 this.stuage=stuage;
14 }
15
16 public String getStudentName(){
17 return stuname;
18 }
19 public String getStudentId(){
20 return stuid;
21 }
22 public int getStudentAge(){
23 return stuage;
24 }
25
26}
27
28public class Constructor_OverloadingExample{
29 public static void main(String[] args){
30 Student stu=new Student();//calling the default constructor
31 Student student=new Student("Khubaib","CSC-17F-129",22);//calling a parameterized constructor with sets the value of parameters
32 System.out.println("Student Name: "+student.getStudentName());
33 System.out.println("Student ID: "+student.getStudentId());
34 System.out.println("Student Age: "+student.getStudentAge());
35
36
37 }
38}
1Yes, the constructors can be overloaded by
2changing the number of
3arguments accepted by the constructor
4or by changing the data type of
5the parameters