Reputation: 1
In the following program the display method is not part of Student4 constructor. So, when the method display is called using the Student4 constructor object does a default constructor invokes the display method?
class Student4 {
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display() {
System.out.println(id+" "+name);
}
public static void main(String args[]) {
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Upvotes: 0
Views: 88
Reputation: 5023
Java creates default constructor itself if no constructor defined in class but if you defined parametrized constructor you have to create default constructor
public static void main(String args[]) {
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
// if you create default constructor it will give you compile time issue
// The constructor Student4() is undefined
Student4 s3 = new Student4();
}
When you create any instance of class, attributes and methods are the part of your object so your object is responsible to call your method not constructor.
Upvotes: 0
Reputation: 6525
As I understand , if you are not defining any explicit constructor then the default constructor will created. Here you have already declared a parameterized constructor, so here it will not create any default constructor.
Upvotes: 0
Reputation: 15837
So, when the method display is called using the Student4 constructor object
You are not calling the display
function using the Student4 constructor
, but using the objects s1
and s2
, that you constructed using your custom constructor.
Upvotes: 1
Reputation: 4076
Student4(int i,String n){
id = i;
name = n;
display();
}
now, your display method is called in your custom constructor. Cheers!
Upvotes: 0
Reputation: 95968
So, when the method display is called using the Student4 constructor object does a default constructor invokes the display method?
No. There's no default constructor in your class since you explicitly declared your own parameterized constructor. A default constructor is a constructor that have no parameter.
Methods are never part of a constructor. The constructor is a special method that's used to set initial values for field variables. Constructors are there to create an instance of a class, so when an object is created, Java calls the constructor first.
Upvotes: 6