The result of this code is different depend on type of reference variable does this mean variables (int a) are bounded in static way
class A{
int a = 10;
}
public class Main extends A {
int a = 30;
public static void main(String[] args){
A m = new Main();
System.out.println("A : " + m.a);
}
}
This is not just like static
or dynamic binding
. There is no polymorphism
for fields
in Java, only for methods
.
Variables decisions are always taken at compile-time
.
So, during the upcasting
base class variable will be taken.
The variable m
you have declared is of type A
so the output would be 10
. Instead if you have initialized m
as Main m = new Main();
, then the output would have been 30
. This is because, the object is of type Main
and since Main
also has a field a
, this would override the parent field a
.
You have two object's type ( A, Main
) both from them have their own meaning for a variable a
, so when your variable m has type A
you get value 10
and if variable m has type Main
you will get value 30
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.