You are not logged in. Please login at to post your questions!


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




    public static void main(String args[]) 
        SuperTest t = new SuperTest();;


how can i acces x of super1 class

asked 26 May '12, 17:09

ramashankar72's gravatar image

accept rate: 0%

edited 26 May '12, 18:08

ritesh_gupta's gravatar image

5★ritesh_gupta ♦

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

answered 26 May '12, 20:17

betlista's gravatar image

3★betlista ♦♦
accept rate: 11%


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

(26 May '12, 22:06) ritesh_gupta ♦5★

Exactly. Methods are overridden during inheritance, not instance variables. Accessing an instance variable from its subclass can be made possible with a simple cast.

(27 May '12, 00:38) adityatj2★

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.


answered 18 Jun '12, 10:58

teli's gravatar image

accept rate: 0%


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 {
    void foo() {
        System.out.println( "BA" );

you can try, that this really prints BA and it's not possible to call using BA instance !!!

(18 Jun '12, 13:43) betlista ♦♦3★

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. :)

(18 Jun '12, 14:40) teli0★
toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here



Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text]( "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:


question asked: 26 May '12, 17:09

question was seen: 1,089 times

last updated: 18 Jun '12, 15:50