Super and this call constructor in JAVA

Reprinted from: https://blog.csdn.net/u014042146/article/details/48374087, except for a few minor changes to individual comments, the others have not changed. It is recommended to run the code again and think clearly about the logic.

 

There can only be one of this and super in the constructor, and both must be the first line in the constructor.

The super keyword, through which subclasses can call the constructor of the superclass.

 

1. When the constructor of the parent class is a parameterless constructor, in the constructor of the subclass, even if you do not write super() to call the constructor of the parent class, the compiler will not report an error, because the compiler will default to Calls the no-argument constructor of the parent class.

class hood {
    public hood(){
        System.out.println("1");
    }
}
class hood2 extends hood{
    public hood2(){
        System.out.println("2");
    }
    
}
public class TEST {
    public static void main(String[] args){
        hood2 t = new hood2();
    }
}

The result of running this code is: 1 2

 

 

2. When the constructor of the parent class is a constructor with parameters, if super() is not written in the constructor of the subclass to call the constructor of the parent class, the compiler will report an error, and super() cannot be omitted at this time.

class hood {
    public hood(int i){
        System.out.println("1"+i);
    }
}
class hood2 extends hood{
    public hood2(){
        super(5);
        System.out.println("2");
    }
    
}
public class TEST {
    public static void main(String[] args){
        hood2 t = new hood2();
    }
}

The result of running this code is: 15 2

 

Then there is the this keyword, which can be understood as it can call its own other constructors, see the following code:

class Father {
       int age;       // age 
      int hight;     // body height
  
      public Father() {
          print();
          this .age=20;    // initialize the value of age here 
      }
      
    public Father( int age) {
          this ();       // Call your own first constructor, the following two statements do not execute 
         this .age = age;
         print();
     }

     public Father( int age, int hight) {
          this (age);    // Call your own second constructor, the following two statements do not execute 
         this .hight = hight;
         print();
     }
 
     public void print() { 
         System.out.println("I'am a " + age + "岁 " + hight + "尺高 tiger!");
     }
     public static void main(String[] args) {
         new Father(22,7);
     }
 }

The result of running this code is:

 

I'am a 0-year-old 0-foot tall tiger!
I'am a 022-year-old 0-foot tall tiger!
I'am a 22-year-old 7-foot tall tiger!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325682944&siteId=291194637