×

multi level inheritence java

 1 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 asked 26 May '12, 17:09 23●4●4●6 accept rate: 0% 3.7k●4●25●49

 1 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 16.9k●49●115●225 accept rate: 11% 1 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) 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★
 0 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 0★teli 1●1●1●1 accept rate: 0% 1 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 !!! (18 Jun '12, 13:43) 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 community wiki:
Preview

By Email:

Markdown Basics

• *italic* or _italic_
• **bold** or __bold__
• 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:

×1,208

question asked: 26 May '12, 17:09

question was seen: 1,089 times

last updated: 18 Jun '12, 15:50