I'm looking at some past papers for an exam and have a problem with the following answers to a question (answers are beside output in the main method) that you have to give the output for. I think that when you upcast in this manner A a=(A)b if you call a.aMethod, if the method appears in both classes but is static in the above class, it will use that method. It will access the variables from the class above, with a.aVariable, but will you use the methods in the original class (and the variables in the original class if called from the method) if the method is not static.
I've looked on the Web, in books and searched the forum but can't seem to find anything advanced enough that explains this in any way. If anyone has any knowledge of this or any URL's to anything I would be very grateful, as I need to read up on this subject. I want to understand this fully and what is happening in memory as well if that's possible.
Thanks a lot.
Code:
public class Q1a {
public Q1a() {
}
public static void main(String[] args) {
B b =new B();
System.out.println("i)"+b.i);//answer is 2
System.out.println("ii)"+b.f());//B
System.out.println("iii)"+b.g());//4
A a=(A)b;
System.out.println("iv)"+a.i);//1
System.out.println("v"+a.f());//A
System.out.println("vi)"+a.g());//4
}
}
class A{
static char f(){
return 'A';
}
int i=1;
int g(){
return i;
}
}
class B extends A{
static char f(){
return 'B';
}
int i=2;
int g(){
return 2*i;
}
}
Thanks a lot.