Details of the auto generated constructor in Java

  • 2020-07-21 08:15:05
  • OfStack

Details of the auto-generated constructor in Java

Each class automatically generates a no-parameter constructor without declaring a constructor, but not if class 1 declares a constructor. The proof is as follows:

Case 1:


class person 
{ 
  person(){System.out.println(" The parent class -person");} 
  person(int z){} 
} 
class student extends person 
{ 
// student(int x ,int y){super(8);} 
} 
 
class Rt 
{ 
  public static void main(String[]args) 
  { 
    student student_dx=new student();// create student The object of the class  
  } 
} 
// The output : The parent class -person 

Example 2:


class person 
{ 
  person(){System.out.println(" The parent class -person");} 
  person(int z){} 
} 
class student extends person 
{ 
  student(int x ,int y){super(8);} 
} 
 
class Rt 
{ 
  public static void main(String[]args) 
  { 
    student student_dx=new student(3,4);// create student The object of the class  
  } 
} 
// No output  

Example 1 :student class automatically generates student() {super(); 'super()' is the constructor used to call the parent class.

The person() method in Example 2 is not called, indicating that the student class does not generate student(){super(); Because the student class has declared the constructor, the default constructor with no arguments is not generated.

For example:


class person 
{ 
  person(int z){} 
} 
class student extends person 
{ 
 
} 
 
class Rt 
{ 
  public static void main(String[]args) 
  { 
    student student_dx=new student();// create student The object of the class  
  } 
} 
/* An error : 
exercise14.java:8:  Can't find sign  
 Symbol:   The constructor  person() 
 Location:   class  person 
class student extends person 
^ 
1  error  
*/ 

Note :student class generates 1 student(){super(); }, but since the person class has already declared the constructor, the default constructor with arguments has not been generated.

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: