继承能不能访问到父类中的私有属性,重写父类的私有方法为什么加不上重写的注解

子类是不能直接访问父类的私有方法、属性的。私有属性可以继承到,但是无法直接访问。想要访问私有属性还需要在父类中添加set、get方法,在子类中通过继承的父类的set、get方法可以进行访问相应的私有属性。所以在子类中重写父类的私有方法的时候不能加上重写的注解,因为无法访问到父类的私有方法,重写父类的私有方法相当于在子类中添加子类特有的方法,所以不能称之为重写。下面是详细的例子

public class Student extends Human {
     

    public static void main(String[] args) {
     
        Student student = new Student();
        student.setId("1020");
        System.out.println(student.getId());//输出结果为1020,说明子类可以通过set、get方法访问到私有属性

        student.eat(23);//调用重写的eat方法
        student.eat("屎");//调用继承的父类的eat方法
    }

/*
无法对父类中的私有方法进行重写,只能“初”写
*/
    @Override
    public void eat(int num) {
     
        System.out.println("重写的eat方法" + num);
    }
}

class Human {
     
    String name;//姓名
    int age;//年龄
    char gender;//性别
    private String id;//ID

    public Human() {
     
    }

    public Human(String name, int age, char gender) {
     
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

    public Human(String name, int age, char gender, String id) {
     
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.id = id;
    }

    public String getId() {
     
        return id;
    }

    public void setId(String id) {
     
        this.id = id;
    }

    private void eat() {
     
        System.out.println("父类中的吃方法");
    }

    public void eat(String name) {
     
        System.out.println("吃" + name);
        eat();//子类可以通过继承的父类的其他方法调用私有方法
    }

    void eat(int num) {
     
        System.out.println("吃" + num + "号菜");
    }

}

输出结果为:
1020
重写的eat方法23
吃屎
父类中的吃方法

继承能不能访问到父类中的私有属性,重写父类的私有方法为什么加不上重写的注解_第1张图片
结论:子类可以通过访问父类提供的set、get方法来实现访问父类中的私有属性的操作;对于有私有属性的父类必须提供空参的构造器,这个构造器为子类的默认构造器(子类默认构造器为空参构造器,而空参构造器的第一行默认为super();所以对于父类提供构造器的时候必须要有空参构造器不然会报错);对于重写父类中的私有方法实际上是不靠谱的说法,(因为子类无法直接访问到父类中的私有方法,只能通过父类中的其他方法进行访问)只能说是写一个子类的特有的方法。

你可能感兴趣的:(继承访问父类私有属性,重写父类私有方法,继承重写,java)