Inheritance in Java


From your C++ programming experience you must be aware of the fact that inheritance plays a vital role in Object Oriented Programming. Being a pure object oriented programming language Java also supports inheritance. However, Java directly supports only single inheritance. In other words a sub-class can inherit directly from a single super or parent class. Sub classing from multiple base / super / parent classes is not allowed in Java. This is totally in contrast to C++, where multiple inheritance is allowed.

We use extends keyword to inherit from a super class as under:

public class subClass extends superClass { }

When a class is inherited:
  • All fields and methods are inherited.
  • Public fields and methods of the parent / super class are available to be used in the subclass.
  • Private fields are also inherited, but cannot be accessed by the methods of the subclass.
  • Protected fields can be accessed by the subclass methods.
When the final reserved word is specified on a class specification, it means that class cannot be the parent of any class i.e. a final class cannot be extended.

Each super-class method (except its constructors) can be inherited, overloaded, or overridden, as explained below:

Inherited: If no method with the same name is (re)defined in the subclass, then the subclass has that method with the same implementation as in the super class.

Overloaded: If the subclass defines a method with the same name, but with a different number of arguments or different argument types, then the subclass has two methods with that name: the old one defined by the super class, and the new one defined in the subclass.

Overridden: If the subclass defines a method with the same name, and the same number and types of arguments, then the subclass has only one method with that name: the new one defined in the subclass. A method CANNOT be overridden if it is defined as final in the super class.

Dynamic Binding
In C++, a method must be defined to be virtual to allow dynamic binding. In Java all method calls are dynamically bound unless the called method has been defined to befinal, in which case it cannot be overridden and all bindings are static.

Constructors
A subclass's constructors always call a super class constructor, either explicitly or implicitly. If there is no explicit call (and no call to another of the subclass constructors), then the no-argument version of the superclass constructor is called before executing any statements.