{
int x=1;
}
class Super2 extends Super1
{
int x=2;
}
class SuperTest extends Super2
{
int x=4;
void show()
{
System.out.println(x);
System.out.println(super.x);
}
public static void main(String args[])
{
SuperTest t = new SuperTest();
t.show();
}
}
Threads that @ritesh_gupta is writing about are about methods and while methods are virtual it is a problem, but there is no problem to access x from Super1.
Methods and instance variables are overridden in exactly the same manner during inheritence. For example, if you had a superclass method which was overridden in each of the subclasses, then to make a call to the method in the topmost class, we must use a similar cast.
Exactly. Methods are overridden during inheritance, not instance variables. Accessing an instance variable from its subclass can be made possible with a simple cast.
You are not correct. Let’s assume this class hierarchy
public class Main {
public static void main( final String[] args ) {
final BA instance = new BA();
( (A) instance ).foo(); // prints "BA"
}
}
class A {
void foo() {
System.out.println( "A" );
}
}
class BA extends A {
@Override
void foo() {
System.out.println( "BA" );
}
}
you can try, that this really prints BA and it’s not possible to call A.foo() using BA instance !!!