Reputation: 323
Can anyone clarify me. Here instance method is overridden but variable is not.
output is: B 10
class A{
int i=10;
public void name(){
System.out.println("A");
}
}
class B extends A{
int i=20;
public void name(){
System.out.println("B");
}
}
public class HelloWorld {
public static void main(String[] args){
A a = new B();
a.name();
System.out.println(a.i);
}
}
Upvotes: 3
Views: 116
Reputation: 2876
In Java instance variables cannot be overridden, only methods can be overridden. When we declare a field with same name as declared in super class then this new field hides the existing field. See this Java doc Hiding Fields.
Upvotes: 1
Reputation: 3412
You cannot override attribute, you can only override method:
public class A{
private int i=10;
public void name(){
System.out.println("A");
}
public int getI(){
return i;
}
}
public class B extends A{
private int i=20;
public void name(){
System.out.println("B");
}
@Override
public int getI(){
return i;
}
}
public class HelloWorld {
public static void main(String[] args){
A a = new B();
a.name();
System.out.println(a.getI());
}
}
In your example, you define variable a
as type A
so the i
value in B
is ignored.
Upvotes: 1
Reputation: 234665
You are absolutely correct. Methods are overridden in Java if the parameter list and function names are identical, and the return types are covariant.
i
in the base class is simply shadowed: a.i
refers to the i
member in the base class, since the type of the reference a
is an A
, even though it refers to a B
instance.
Upvotes: 4