java - Why subclasses does not override the value of their superclass variable? -
i have 3 classes following, class b , c extending class a. wondering why code not reading value of b , c variables.
public class a{ protected int myvalue = 1; } public class b extends a{ private int myvalue = 2; } public class c extends a{ private int myvalue = 3; }
body of main method
arraylist<a> mylist= new arraylist(); mylist.add(new b()); mylist.add(new c()); for(int =0;i<mylist.size();i++) system.err.println("value is:" + mylist.get(i).myvalue);
output
1 1
from oracle website:
within class, field has same name field in superclass hides superclass's field, if types different. within subclass, field in superclass cannot referenced simple name. instead, field must accessed through super, covered in next section. speaking, don't recommend hiding fields makes code hard read.
you shadowing field myvalue
, not overriding it, believe want
public class a{ protected int myvalue = 1; } public class b extends a{ public b() { myvalue = 2; } } public class c extends a{ public c() { myvalue = 3; } }
also, please don't utilize raw types
// arraylist<a> mylist = new arraylist(); arraylist<a> mylist = new arraylist<>(); // <a> on java 5 , 6
java
No comments:
Post a Comment