我在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;
无法从孩子转为父母
答案 0 :(得分:0)
我的日食中没有发现编译错误。 我也将输出打印到控制台。
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
答案 1 :(得分:0)