简体   繁体   English

在超类和方法调用中声明一个子类

[英]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));
    }
}

Why there was a compile error on that line? 为什么该行有编译错误? I declare x2 as a class of Y, which I should able be to call all the function on class Y, why in blueJ it display 我将x2声明为Y类,我应该可以调用类Y上的所有函数,为什么在blueJ中显示它

" cannot find symbol - method m_Y(int)"

If you want to declare x2 as a type of X but use it as a type Y, you will need to cast x2 to type Y each time you want to do that. 如果要将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));
    }
}

Even though the object stored in x2 is actually Y you have it declared x2 as X . 即使存储在x2的对象实际上是Y你也可以将x2声明为X There is no way for compiler to know that you have Y object in your X reference and there is no m_Y method in X. 编译器无法知道X引用中有Y对象,并且X中没有m_Y方法。

TLDR : Do a class cast: ((Y)x2).m_Y(0) TLDR :做一个类演员: ((Y)x2).m_Y(0)

Because the class Y is an child class of X so you cannot call a child method from parent instance. 因为类Y是X的子类,所以不能从父实例调用子方法。

You define x2 as X and X is parent of Y that mean x2 is an instance of X or Y 您将x2定义为X,X是Y的父级,表示x2是X或Y的实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM