Super keyword notes in Java

   After the subclass has overridden the method of the parent class, the object of the subclass will be inaccessible to the overridden method of the parent class. How to access this? Java provides a super keyword to access methods or member variables of the parent class.

  1. Use the super keyword to call the member variables and member methods of the parent class.
      Syntax format:

super. member variable
super. member method (parameter 1, parameter 2, ...);

Examples:

//父类
public class Animal {
    
    
    //定义一个成员变量name
    String name = "牧羊犬";
    //定义一个动物跑的方法
    public void run(){
    
    
        System.out.println("动物地上跑...");
    }
}
//Dog类继承父类Animal 
public class Dog extends Animal {
    
    
    String name = "哈士奇";
    //重写父类的方法
    public void run(){
    
    
        //调用父类的run()方法
        super.run();
    }
    //打印名字的方法
    public void showName(){
    
    
        System.out.println("自己的name:" + name + "|" + "父类的name:" + super.name );
    }
}
//测试类
public class Test {
    
    
    public static void main(String[] args) {
    
    
        //实例化一个dog对象
        Dog dog = new Dog();
        //调用run()方法
        dog.run();
        //调用showName()方法
        dog.showName();
    }
}

Output result:
Insert picture description here
2. Use the super keyword to access the construction method of the parent class.
  Syntax format:

super(parameter 1, parameter 2,...);

Examples:

//父类Animal
public class Animal {
    
    
    //定义一个成员变量name
    String name;
    //定义一个有参构造方法
    public Animal(String name) {
    
    
        this.name = name;
        System.out.println(this.name);
    }
}
//Dog类继承Animal
public class Dog extends Animal {
    
    

    public Dog() {
    
    
        //调用父类的有参构造方法
        super("藏獒");
    }
}
//测试类
public class Test {
    
    
    public static void main(String[] args) {
    
    
        //实例化一个dog对象
        Dog dog = new Dog();
    }
}

Output result:
Insert picture description here
    In the no-parameter construction method of the Dog() class, the super keyword is used to call the parameterized construction method of the parent class. When the construction method of the Dog class is called, the construction method of the parent class will be called. It should be noted that the code for the super keyword to call the constructor of the parent class must be in the first line of the constructor of the subclass and can only appear once.

Come on! ! !

Guess you like

Origin blog.csdn.net/qq_42494654/article/details/109252346