关于Java继承中的Pivate变量

来源:互联网 发布:设置淘宝客优惠券教程 编辑:程序博客网 时间:2024/05/16 12:58

继承中有个很有趣的地方,private method不会被继承到子类当中,但是继承到子类中的public方法却可以使用private方法,因为它是类接口的一部分。那么private变量呢?是否private变量被继承到子类里了呢

abstract class Event {
    
private int eve; // eve is a private variable

    
public void setEve(int e) {
                   eve 
= e;
                   setEve();
                   System.out.println(eve);
        }


    
private void setEve() {
        
// ...
        }

}


public class Inner extends Event {
    
public static void main(String[] argu) {
                    Inner a 
= new Inner();
                    a.setEve(
2); // use a.eve
                   
// a.setEve(); error: setEve() is a private method
        }

}

 

结果很明显,private变量被保留下来了,因为在继承下来的public或者protected的方法中可能使用到它.只是对于子类本身的方法这个变量是不可见的。
原创粉丝点击