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 to share