HARZI
HARZI

Reputation: 191

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

" cannot find symbol - method m_Y(int)"

Upvotes: 3

Views: 263

Answers (3)

Khate
Khate

Reputation: 369

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

You define x2 as X and X is parent of Y that mean x2 is an instance of X or Y

Upvotes: 0

Andy Guibert
Andy Guibert

Reputation: 42926

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.

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));
    }
}

Upvotes: 2

dimoniy
dimoniy

Reputation: 5995

Even though the object stored in x2 is actually Y you have it declared x2 as 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.

TLDR: Do a class cast: ((Y)x2).m_Y(0)

Upvotes: 0

Related Questions