English English

Inheritance in Java

In Java you can make classes inherit properties(methods, variables, etc.) of another class.

Classes that inherit properties are called sub classes (child classes) and classes that are inherited from are called superclasses. A subclass can only inherit one superclass.

Extend class (Keyword)

Use the keyword extends to inherit the properties of a class. Here is an example:

class Super {
   .....
}
class Sub extends Super {
   .....
}

The Superclass reference variable can hold the subclass object, but using that variable you can access only the members of the superclass, so to access the members of both classes it is recommended to always create reference variable to the subclass.

Super (Keyword)

For the following scenarios the super keyword is used. The super keyword is also similar to this keyword. 

  • Used to differentiate the members of superclass from the members of subclass, if they have same names.

  • Used to invoke the superclass constructor from subclass.

Differentiating the Members

If a class is inheriting the properties of another class. And if the members of the superclass have the names same as the sub class, to differentiate these variables we use super keyword as shown below.

Invoking Superclass Constructor

If a class is inheriting the properties of another class, the subclass automatically acquires the default constructor of the superclass. But if you want to call a parameterized constructor of the superclass, you need to use the super keyword as shown below. Here is an example:

super(values);

Relationship IS-A

This object is a type of that object. Let us see how the extends keyword is used to achieve inheritance.

public class Animal {
}

public class Mammal extends Animal {
}

public class Reptile extends Animal {
}

public class Cat extends Mammal {
}

Now, based on the above example, in Object-Oriented terms, the following are true −

  • Animal is the superclass of Mammal class.
  • Animal is the superclass of Reptile class.
  • Mammal and Reptile are subclasses of Animal class.
  • Dog is the subclass of both Mammal and Animal classes.

Now, if we consider the IS-A relationship, we can say −

  • Mammal IS-A Animal
  • Reptile IS-A Animal
  • Dog IS-A Mammal
  • Hence: Dog IS-A Animal as well

With the use of the extends keyword, the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass.

We can assure that Mammal is actually an Animal with the use of the instance operator.

Usamos cookies en nuestro sitio web. Algunas de ellas son esenciales para el funcionamiento del sitio, mientras que otras nos ayudan a mejorar el sitio web y también la experiencia del usuario (cookies de rastreo). Puedes decidir por ti mismo si quieres permitir el uso de las cookies. Ten en cuenta que si las rechazas, puede que no puedas usar todas las funcionalidades del sitio web.