1 class A {
      2     private int i;
      3
      4     public void setI(int i) {
      5         this.i = i;
      6     }
      7
      8     public int getI() {
      9         return i;
     10     }
     11 }
     12
     13 class B extends A {
     14     public void print() {     //父类A中的变量i是私有的,所以B中应该没有i,
     15         setI(8);            //setI()和getI()操纵的是哪个i  ?????
     16
     17         System.out.println(getI());
     18     }
     19 }
     20
     21 public class PrivateTest {
     22     public static void main(String[] args) {
     23         B b = new B();
     24
     25         b.print();
     26 //      b.i = 0;   无法访问
     27     }
     28 }私有变量是否是可以被继承,但是,不能被访问????

解决方案 »

  1.   

    私有变量是否是可以被继承, 可以.
    通过public/protected方法访问, 如setI(int ), getI()
      

  2.   

    私有变量通过方法来访问,就体现出了封装性,因为你的方法是public的
      

  3.   

    私有变量是不可以被继承的,子类中不可以直接访问, 可以用public/protected方法访问, 如你setI(int ), getI()
      

  4.   

    子类想用父类的私有变量只能通过父类的public成员方法去访问
      

  5.   

    可以继承,
    b.i = 0;   无法访问
    说明i是私有的
    必须通过
    public int getI()
    {
    return i;
    }或
    protected int getI()
    {
    return i;
    }