Reputation: 1241
Given the follwoing Code:
public class A {
int at=2;
public int m(int i){return at+i;}
}
class B extends A {
int at=3;
public int m(int i){return at+5*i;}
}
public class Main {
public static void main(String args[]){
A x = new B();
System.out.println("Output "+x.m(x.at));
}
}
The output is 13.
How does it work? I know that it takes method from B, but what about arguments?
Upvotes: 3
Views: 64
Reputation: 2169
Actually you have two at
fields one declared in A
and other in B
. Method m
in A
refers to field at
in A
; method m
in B
refers to filed at
in B
. Method is overridden, field is not. x
is declared as instance of A
so x.at
is 2. When you call method m
the overridden method is called (B.m(2)
) so you get 3+5*2 = 13.
In such cases Java Language specification should tell you what's right and why. Answer to this question can be found in 8.3. Field Declarations
If the class declares a field with a certain name, then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in superclasses, and superinterfaces of the class.
A hidden field can be accessed by using a qualified name (§6.5.6.2) if it is static, or by using a field access expression that contains the keyword super (§15.11.2) or a cast to a superclass type.
cast to a superclass type is your case.
Upvotes: 3
Reputation: 1301
Variables does not override like methods. So variables value depends on Reference Variable not on the instance being referenced by this reference variable.
example: in your case. In main() method
A x =new B();
reference variable x is of type A and it hold a reference of an instance of type B.
So as X is of type A. WhenEver you write x.at it being refer Class A variable.
Upvotes: 1
Reputation: 12939
Look at expression: x.m(x.at)
. Since x
is cdeclared as A
, x.at
will refer to at
field in A
.
However, it gets more complicated when it comes to methods. Although x
is declared as A
, x
in fact is of type B
, so method m
will be called from x
's acctual class, B
.
Maybe this coud help.
Upvotes: 6