【问题标题】:declaring a subclass in superclass and method calling在超类和方法调用中声明子类
【发布时间】:2015-07-10 13:48:02
【问题描述】:
    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)"

【问题讨论】:

  • m_Y 没有为X 定义。在命名方法等时使用 Java 命名约定。
  • 您将x2 声明为X 类型。 Java 是strongly typed language。

标签: java inheritance polymorphism subclass superclass


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

      您将 x2 定义为 X 并且 X 是 Y 的父级,这意味着 x2 是 X 或 Y 的实例

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-07
        • 2011-10-24
        • 2020-12-10
        • 1970-01-01
        • 2012-04-18
        相关资源
        最近更新 更多