JAVA完美编程中写到:The derived class inherits all the public methods, all the public and private
instance variables, and all the public and private static variables from the base class and can
add more instance variables, more static variables, and more methods.
问题:如果父类有一个私有成员变量,那么子类也有着和父类相同名字的私有成员变量,因为他从父类中继承了PRIVATE INSTANCE VARIABLE?public class PrivateMethodInheritanceBaseClass {
private int variable1;
}
public class PrivateMethodInheritance extends PrivateMethodInheritanceBaseClass {
public static void main(String [] args){
PrivateMethodInheritance obj=new PrivateMethodInheritance();
                   //如果PrivateMethodInheritance类中也继承了VARIABLE1,那么如何访问这个变量?
//obj.variable1 is error!
}
}

解决方案 »

  1.   

    私有变量是不可以继承的。因为private的东西外边的类是看不到的,就相当于隐藏了一样。建议LZ好好看看private,public,package,default属性问题。
      

  2.   


    import java.lang.reflect.Field;class PrivateMethodInheritanceBaseClass {
        private int variable1;
        public int getVariable1() {
    return variable1;
    }
    }
    public class PrivateMethodInheritance extends PrivateMethodInheritanceBaseClass {
        public static void main(String [] args){
            PrivateMethodInheritance obj=new PrivateMethodInheritance();
        
            try {
    Field field= PrivateMethodInheritanceBaseClass.class.getDeclaredField("variable1");
    field.setAccessible(true);
    field.setInt(obj, 10);
    } catch (SecurityException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (NoSuchFieldException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IllegalArgumentException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IllegalAccessException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
            System.out.println(obj.getVariable1());
                       //如果PrivateMethodInheritance类中也继承了VARIABLE1,那么如何访问这个变量?
            //obj.variable1 is error!
        }
    }
      

  3.   

    私有的东西不继承的说法来自<java语言规范>,以及james gosling等人的著作
      

  4.   

    摘自java语言规范:注意红色那句话
    A private class member or constructor is accessible only within the body of the top level class  that encloses the declaration of the member or constructor. It is not inherited by subclasses. In the example:
        class Point {       Point() { setMasterID(); }       int x, y;       private int ID;       private static int masterID = 0;       private void setMasterID() { ID = masterID++; }    }
    the private members ID, masterID, and setMasterID may be used only within the body of class Point. They may not be accessed by qualified names, field access expressions, or method invocation expressions outside the body of the declaration of Point.
      

  5.   

    晕~~~~~弄得真难看,红色那句话It is not inherited by subclasses.
    private的东西可以使用反射调用
    但是看LZ的意思好像是误认为可以继承private的东西了