在超类中声明子类并调用方法
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 的 class,我应该能够调用 class Y 上的所有函数,为什么在 blueJ 中它显示
" cannot find symbol - method m_Y(int)"
尽管存储在 x2
中的对象实际上是 Y
,但您已将其声明为 x2
为 X
。编译器无法知道您的 X
引用中有 Y
对象,并且 X 中没有 m_Y 方法。
TLDR:进行 class 转换:((Y)x2).m_Y(0)
如果您想将 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));
}
}
因为 class Y 是 X 的子 class,所以您不能从父实例调用子方法。
您将 x2 定义为 X 且 X 是 Y 的父级,这意味着 x2 是 X 或 Y 的实例
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 的 class,我应该能够调用 class Y 上的所有函数,为什么在 blueJ 中它显示
" cannot find symbol - method m_Y(int)"
尽管存储在 x2
中的对象实际上是 Y
,但您已将其声明为 x2
为 X
。编译器无法知道您的 X
引用中有 Y
对象,并且 X 中没有 m_Y 方法。
TLDR:进行 class 转换:((Y)x2).m_Y(0)
如果您想将 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));
}
}
因为 class Y 是 X 的子 class,所以您不能从父实例调用子方法。
您将 x2 定义为 X 且 X 是 Y 的父级,这意味着 x2 是 X 或 Y 的实例