Why are we not able to override an instance variable of a super class in a subclass?
Because instance variables CANNOT be overridden in Java. In Java, only methods can be overridden. When you declare a field with the same name as an existing field in a superclass, the new field hides the existing field. The existing field from the superclass is still present in the subclass, and can even be used ...
When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one of the superclasses, then it will generate an error.
Because variables in Java do not follow polymorphism and overriding is only applicable to methods but not to variables. And when an instance variable in a child class has the same name as an instance variable in a parent class, then the instance variable is chosen from the reference type.
3) An instance method cannot override a static method, and a static method cannot hide an instance method. For example, the following program has two compiler errors.
He perhaps meant to try and override the value used to initialize the variable. For example,
public abstract class A { String help = "**no help defined -- somebody should change that***"; // ... } // ... public class B extends A { // ILLEGAL @Override String help = "some fancy help message for B"; // ... }
public abstract class A { public String getHelp() { return "**no help defined -- somebody should change that***"; } // ... } // ... public class B extends A { @Override public String getHelp() { return "some fancy help message for B"; // ... }
Because if you changed the implementation of a data member it would quite possibly break the superclass (imagine changing a superclass's data member from a float to a String).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With