When you override a method you must keep the method's signature and can't reduce its visibility. Now I tried what happends when I do this with attributes. I was surprised - IT WORKS! Look yourself:
public class A {
public Integer myAttribute;
}
public class B extends A {
public String myAttribute;
}
public class Main {
public static void main(String[] args) {
B b = new B();
b.myAttribute = "myString";
((A) b).myAttribute = 1337;
System.out.println(b.myAttribute);
System.out.println(((A)b).myAttribute);
}
}
So it is possible to write an attribute in a subclass with the same attibute name as in the superclass, but you can use different visibility (modifier) and type. So I would say that the attributes in superclass and subclass are almost completely independend from each other.
Now if you really use the same attribute name in superclass and subclass you effectively hide the superclass's attribute. When accessing the attribute using the subclass, you get the subclass's attribute. But the superclass's attribute is there, too! You have to perform a cast to access the superclass's attribute from outside. From inside the "super" keyword should be usefull.
Question 1: Now basically you have two different attributes with the same name. Doesn't this break LSP?
Why I came to this detail is this: I am experimenting with an self written persistence framework. I want to read the complete internal state of an object and persist that state. I read all attribute's values via reflexion, starting at the subtype and traversing over the superclasses. Now if there are two attributes with the same name in superclass and subclass I have to remember the class which declares an attribute to be able to map the attributes values to the right attributes and restore an object's state.
Question 2: Any other ideas how to deal with this detail? Question 3: How do other persistence frameworks handle this detail?
I never saw this detail in use. Maybe writing two attributes with the same name is a bit ugly, but it is possible and any persistence framework may be confronted with it. Maybe there are situations where this technique might be usefull.
Thans in advance.