首页 > 技术文章 > **super关键字**

z-hou 2021-03-12 23:26 原文

从上述代码可以看出,当子类重写父类方法时,子类的对象将无法访问父类的对象

解决这个问题Java提供了一个关键字super来访问父类的成员

 

使用super来调用父类的成员变量和成员方法,格式

super.成员变量
super.成员方法(参数1,参数2.....)
public class Animal {
    String name = "动物";
    //定义动物叫
    void shout(){
        System.out.println("动物发出叫声");
    }
}

public class Dog extends Animal{
    String name = "犬类";
    void shout(){
        super.shout();//访问父类的成员方法
    }
    //打印name的方法
    void printName(){
        System.out.println("name="+super.name);
    }
}
//测试类
public class C7 {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.shout();
        dog.printName();

    }

}

super在构造器中的作用

 
//人 父类
public class Person {
    public Person() {
        System.out.println("the constructor of person");
    }
}

public class Student extends Person{
    public Student() {
        System.out.println("the constructor of student");
    }
}
//测试类
public class C7 {
    public static void main(String[] args) {
        Student student=new Student();
    }
}

Student student=new Student();

当实例化对象的时候最先调用的就是构造器

猜猜看 输出是什么

the constructor of person the constructor of student

最先输出的是 the constructor of person

说明了什么

public class Student extends Person{
    public Student() {
    //隐藏代码super();
        System.out.println("the constructor of student");
    }
}

super 跟前面学的this很像

它必须要位于无参构造的第一行

当然如果我的父类只有有参构造,那子类会怎么样?

很显然,会报错

你父类就没有无参构造,你子类怎么调用

会直接报错,当然你可以调用有参显示调用

 2021-03-12 23:26:09

推荐阅读