Subclass declaration in superclass and method invocation

    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 was there a compilation error on this line? I declare x2 as class Y, which I would have to call the whole function of class Y, so in blueJ it displays

" cannot find symbol - method m_Y(int)"

      

+3


source to share


3 answers


If you want to declare x2 as type X, but use it as type Y, you will need to use x2 to type Y every time you want to do this.



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


source


Even if the object is stored in x2

, actually Y

, you declared x2

both X

. There is no way for the compiler to know that you have Y

an object in X

references and there is no way for M_Y in X.



TL; DR : execute the class:((Y)x2).m_Y(0)

0


source


Since class Y is a child of class X, so you cannot call a child method from the parent instance.

You define x2 to be X and X is the parent of Y, which means x2 is an instance of X or Y

0


source







All Articles