Avoid hiding fields as it makes code difficult to read!
Shadowing declarations
If a declaration of a type (such as a member variable or a parameter name) in a particular scope (such as an inner class or a method definition) has the same name as another declaration in the enclosing scope, then the declaration shadows the declaration of the enclosing scope.
public class Animal {
public String description = "This is an Animal";
}
class Cat extends Animal {
public String description = "This is the Cat";
public void printDescription(String description) {
System.out.println(description); // Shadows declaration output: "This is the Lion"
System.out.println(this.description); // Shows declaration output: "This is the Cat"
System.out.println(super.description); // Shows super declaration output: "This is an Animal"
}
}
...
public static void main( String[] args ) {
Cat cat = new Cat();
cat.printDescription("This is the Lion");
}
Hiding static methods
If asubclass
defines a static
method with the same signature as a static
method in the superclass
, then the method in the subclass
hides the one in the superclass
:
public class Animal {
public static void hideMe() { System.out.println("hideMe in Animal"); }
}
class Cat extends Animal {
public static void hideMe() { System.out.println("hideMe in Cat"); }
}
class Lion extends Cat {}
...
public static void main( String[] args ) {
Animal.hideMe(); // Contains static method. output: "hideMe in Animal"
Cat.hideMe(); // Hides static method of Animal. output: "hideMe in Cat"
Lion.hideMe(); // Inherits static method of Cat. output: "hideMe in Cat"
}
static
methods in interfaces are never inherited. Whereas classes inherit static
methods of their parents.Hiding fields
Within aclass
, a field that has the same name as a field in the superclass
hides the superclass's field,even if their types are different!Within the
subclass
, the field in the superclass
cannot be referenced by its simple name. Instead, the field must be accessed through super
.Once more: Fields of
subclass
with the same name hide superclass
fields, there no fields overriding!
public class Animal {
public String description = "This is an Animal";
}
class Cat extends Animal {
public String description = "This is the Cat";
}
...
public static void main( String[] args ) {
Animal animal = new Cat();
System.out.println(animal.hiddenDescription); // --> "This is an Animal"
Cat cat = new Cat();
System.out.println(cat.hiddenDescription); // --> "This is the Cat"
}
public class Animal {
public String getDescription() {
return "This is an Animal";
}
}
class Cat extends Animal {
@Override
public String getDescription() {
return "This is the Cat";
}
}
...
public static void main( String[] args ) {
Animal animal = new Cat();
System.out.println(animal.getDescription()); // --> "This is the Cat"
Cat cat = new Cat();
System.out.println(cat.getDescription()); // --> "This is the Cat"
}
No comments:
Post a Comment