Advertisements
Advertisements
Question
Answer the following in brief. Give a program code example wherever applicable.
Constructors cannot be called. Then when do they get executed?
Code Writing
Advertisements
Solution
A constructor is executed automatically when an object of the class is created using the new keyword. It is used to initialize the object. When the object s is created using new Student(), the constructor is automatically invoked.
class Student
{
Student()
{
System.out.println("Constructor executed");
}
public static void main(String[]args)
{
Student s = new Student();
}
}shaalaa.com
Is there an error in this question or solution?
