在父类中声明子类并调用方法

3
    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)"

2
m_Y未为X所定义。在命名方法等时,请使用Java命名约定。 - Reimeus
你将 x2 声明为类型为 X 的变量。Java 是一种强类型语言 - Nir Alfasi
3个回答

2
如果您想将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));
    }
}

0

尽管存储在x2中的对象实际上是Y,但您将其声明为X。编译器无法知道您在X引用中具有Y对象,并且X中没有m_Y方法。

TLDR:进行类转换:((Y)x2).m_Y(0)


0

因为类Y是类X的子类,所以您不能从父类实例调用子方法。

将x2定义为X,而X是Y的父类,这意味着x2是X或Y的实例。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接