[英]declaring a subclass in superclass and method calling
public class Y extends X
{
int i = 0;
public int m_Y(int j){
return i + 2 *j;
}
}
public class X
{
int i = 0 ;
public int m_X(int j){
return i + j;
}
}
public class Testing
{
public static void main()
{
X x1 = new X();
X x2 = new Y(); //this is the declare of x2
Y y2 = new Y();
Y y3 = (Y) x2;
System.out.println(x1.m_X(0));
System.out.println(x2.m_X(0));
System.out.println(x2.m_Y(0)); //compile error occur
System.out.println(y3.m_Y(0));
}
}
为什么该行有编译错误? 我将x2声明为Y类,我应该可以调用类Y上的所有函数,为什么在blueJ中显示它
" cannot find symbol - method m_Y(int)"
如果要将x2声明为X的类型但将其用作类型Y,则每次要执行此操作时都需要将x2转换为类型Y.
public class Testing
{
public static void main()
{
X x1 = new X();
X x2 = new Y(); //this is the declare of x2
Y y2 = new Y();
Y y3 = (Y) x2;
System.out.println(x1.m_X(0));
System.out.println(x2.m_X(0));
System.out.println(((Y) x2).m_Y(0)); // fixed
System.out.println(y3.m_Y(0));
}
}
即使存储在x2
的对象实际上是Y
你也可以将x2
声明为X
编译器无法知道X
引用中有Y
对象,并且X
中没有m_Y方法。
TLDR :做一个类演员: ((Y)x2).m_Y(0)
因为类Y是X的子类,所以不能从父实例调用子方法。
您将x2定义为X,X是Y的父级,表示x2是X或Y的实例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.