Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding a super class's instance variables

Why are we not able to override an instance variable of a super class in a subclass?

like image 399
Warrior Avatar asked Jan 09 '09 11:01

Warrior


People also ask

Can we override instance variables of a superclass?

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 ...

How do you override a superclass method?

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.

Can we override a variable of super class inside the child class?

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.

Can you override an instance method?

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.


2 Answers

He perhaps meant to try and override the value used to initialize the variable. For example,

Instead of this (which is illegal)

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";     // ... } 

One should do

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";     // ... } 
like image 54
Pierre D Avatar answered Sep 20 '22 13:09

Pierre D


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).

like image 30
cletus Avatar answered Sep 16 '22 13:09

cletus