multi level inheritence java

class Super1

{
	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();

	} 
}

how can i acces x of super1 class

1 Like

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.

System.out.println( ((Super1)this).x );
1 Like

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.

Sorry i did n’t consider that . @betlista is absolutely correct:).Can be done directly using System.out.println( ((Super1)this).x );

1 Like

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 !!!

1 Like

I had an instantiation like
A instance = new BA();
( (A) instance ).foo();

in mind. You are right it still prints BA.

Thanks for the correction. :slight_smile: