Java学习笔记-继承(2)

- protected

继承有个特点,就是子类无法访问父类的private字段或者private方法。
这使得继承的作用被削弱了。为了让子类可以访问父类的字段,我们需要把private改为protected

class Person {
    protected String name;
    protected int age;
}

class Student extends Person {
    public String hello() {
        return "Hello, " + name; // 这样就可以了
    }
}

-super() --------------// 调用父类的构造方法

class Student extends Person {
    protected int score;

    public Student(String name, int age, int score) {
        super(name, age); // 调用父类的构造方法Person(String, int)
        this.score = score;
    }
}

猜你喜欢

转载自blog.csdn.net/u013589260/article/details/106062352