Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)"
like image 286
HARZI Avatar asked Sep 01 '26 09:09

HARZI


1 Answers

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));
    }
}
like image 105
Andy Guibert Avatar answered Sep 03 '26 23:09

Andy Guibert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!