Search code examples
javainheritancepolymorphismsubclasssuperclass

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

Solution

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