有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法从子类访问父类变量

我在用java开发下面的程序时理解到两个类Parent和Child,都声明了一个即时变量x 类Child的超类。类Child的实例(对象)将包含变量x的两个实例

因此,我开发了以下程序

class Parent { int x; }
class Child extends Parent { int x; }

class Test {

    public static void main (String args[]) {
        int y;

        Child c = new Child();// A Child object referenced by a variable of type Child
        y = c.x;    // reference to the x of class Child
        y = ((Parent) c).x;     // reference to the x of class Parent

        Parent p = new Child(); // A Child object referenced by a variable of type Parent
        y = p.x;     // reference to the x of class Parent
        y = ((Child) p).x;    // reference to the x of class Child
    }
}

但程序仍然存在编译问题,无法访问父x变量,请建议如何从相同的角度克服

编译错误我在下面的行中看到

y = ((Parent) c).x;

无法从子级强制转换为父级

编译错误图像: compilation error image please open


共 (2) 个答案

  1. # 1 楼答案

    我在eclipse中没有发现编译错误。 我还将输出打印到控制台

    class Parent { int x = 1; }
    class Child extends Parent { int x = 2; }
    
    public class Test {
    
        public static void main (String args[]) {
            int y;
    
            Child c = new Child();// A Child object referenced by a variable of type Child
            y = c.x;    // reference to the x of class Child
            y = ((Parent) c).x;     // reference to the x of class Parent
    
            Parent p = new Child(); // A Child object referenced by a variable of type Parent
            y = p.x;     // reference to the x of class Parent
            y = ((Child) p).x;    // reference to the x of class Child
            
            System.out.println(" child " + y);
            System.out.println( " parent " + y);
        }
    }

    输出:

    孩子2

    家长2

  2. # 2 楼答案

    我只是从你的问题中复制了代码,没有编译错误。我能想到的唯一一种情况是,在不同的包中定义父类和子类,在没有任何访问修饰符(public)的情况下定义变量x,然后在访问变量x时,您将得到编译错误

    enter image description here

    从你问题中的图像中,我看不到家长和家长;在测试类中定义的子类很可能是变量x的包可见性导致编译错误