java如何使子类继承父类的private变量

如何只改动注释的那一句,使得子类能够继承父类的private


public class people {
    private int averHeight=166;
private int getAverHeight() {
    return averHeight;
}
}
class ChinaPeople extends people{
    int height;
    public void setHeight(int h) {
        height=height+averHeight;//非法
        height=h;
    }
    public int getHeighgt() {
        return height;
    }
}
public class Exam {
        public static void main(String args[]) {
            ChinaPeople zhangsan=new ChinaPeople();
            System.out.println(zhangsan.getAverageHeight());
            zhangsan.setHeight(178);
            System.out.println(zhangsan.getHeighgt());
        }
}

private 修饰的变量,只有自己能访问,其他类都不能访问;

子类继承父类,实例化时其实内存中已经有这个父类的私有变量了,只需要 提供public 或 protected的 get方法,子类就可以使用

class people {
    private int averHeight=166;
    public int getAverHeight() {
        return averHeight;
    }
}
class ChinaPeople extends people{
    int height;
    public void setHeight(int h) {
        height=height+getAverHeight();
        height=h;
    }
    public int getHeighgt() {
        return height;
    }
}
public class Exam {
    public static void main(String args[]) {
        ChinaPeople zhangsan=new ChinaPeople();
        System.out.println(zhangsan.getAverHeight());
        zhangsan.setHeight(178);
        System.out.println(zhangsan.getHeighgt());
    }
}

img


如有帮助,欢迎采纳哈!

在这里插入图片描述

本人的开源项目,欢迎star支持下!!!

继承不了的啊~public、protected、private 三者的作用、区别记得吗
要不加个get函数吧