why the output of following program is S1 and not S2 ? please explain. class Question13 { String s = "outer"; public static void main(String args[]) { S2 ob = new S2(); ob.display(); } } class S1 { String s = "S1"; void display() { System.out.println(s); } } class S2 extends S1 { String s="S2"; }
Hi Arno, Is seams that you didn't run the question to see the result. The result is S1 even the object what calls the method is an S2 instance.
Why is this way?
Because the the attributes are linked at compile time. -> not enabled for polymorphism. For the methods instead, the decision (which method to call) is taken at run-time. -> polymorphism enabled
'Make everything as simple as possible, but not simpler.' --Albert Einstein
class Question13 { String s = "outer"; public static void main(String args[]) { S2 ob = new S2(); ob.display(); } } class S1 { String s = "S1"; void display() { System.out.println(s); } } class S2 extends S1 { String s="S2"; }
As said by marc variaables are hidden and not overridden.... since the method called is in Class s1....the instance variable in that class is accesed.. suppose if the method display is in class s2,then the result will be "S2"....
The field that gets accessed is determined at compile time based on the type of the reference used to access it.
Inside a method, a reference to a field always refers to the field declared in the class in which the method is declared, or else to an inherited field if there is no declaration in that class.
hence the field s1 was refered maybe you can comment this line //String s = "S1"; in class s1,and then a compile time error will occur
Actually, variables are not really "overriden," but instead can be "hidden." See JLS 8.3.3.1 and 8.3.3.2.
to add more , it is the member function that can be overridden , or we can Java supports runtime polymorphism for member functions , But it should not be static methods. [ April 18, 2006: Message edited by: faisal usmani ]
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.