Wednesday, September 20, 2006

Implications of Inheritance

In a subclass, you can create a new variable with the same name as an inherited variable, same type or class is not necessary. The subclass uses this variable instead of the inherited variable. This is known as hiding a variable.

Generally, you only need to hide superclass variables in rare situations where the generic class was not well defined, such as when maintaining someone else's code. Variable hiding is not recommended, as it can lead to confusing and ambiguous code.

Java makes a copy of each inherited superclass variable available to each object in a subclass, even if the variable is hidden. To access a specific data member within an inheritance hierarchy, you sometimes need to perform an explicit cast.

Overloading a method is often confused with overriding a method. Overloading is to create methods with the same name as an existing method, but with different arguments. Overloading can happen within a same class or subclasses.

Constructors are not automatically inherited, so subclasses do not automatically receive any constructor implementation code from their superclass, such as initialization code for variables. Java ensures that an object is constructed in the correct order, from its base to its subclass. This is called constructor chaining. If you do not explicitly call a constructor of a superclass, Java automatically calls the no-argument superclass constructor. If the superclass has no such constructor, the class will not compile.

No comments: