Inheritance in Java

Inheritance in java is very simple but userful and power ful. It allows us to extend existing class and reuse the existing code. The
idea of extending class is very simple. If you want to write a class and a similar class already exist with less functionality or properties. You can extend the existing class and can add more fields and methods as well utilizing the existing class fields and methods without write or debug it by yourself. Java allows to derive a class from another class, therefore they inhertits data fields and methods from superclass or base class.

What is a sub class?

A class that is derived from another class is known as sub class, also referred as child class, derived class, extended class and sub type. A subclass extends methods and properties from superclass  as well you can also add new data fields, methods and override the methods of the superclass.

What is a Supper class or Base class?

The class from which a sub class is derived is known as a super class, also referred as base class or parent class. Consider the example bellow. Fruit is the superclass of class Orange and Apple.

Java Inheritance Example

Java Inheritance Example

 

Example 1

Inheritance

Inheritance

Example 2

Inheritance Example

Inheritance Example


Inheritance Main Class

Inheritance Main Class


Inheritance Result

Inheritance Result

Example 3

Inheritance Example

Inheritance Example

Note :

  • A superclass constructor in inherited. They must be invoked explicitly or implicitly
  • super keyword is used to explicitly invoke superclass constructor
  • super must be the first statement in subclass constructor
  • If a superclass is not explicitly invoked then compiler puts super() as the first statement in subclass constructor
  • With super keyword, you can also invoke super class methods
  • Invoking a superclass constructor with its name cause the syntax error
super keyword

use of super keyword

Object class

By defualt Object class is a super class of a class if no inheritance is specified.

Object class

Object class [1]

Object class

Object Class

References

[1] Oracle Official Website, http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
[2] Introduction to Java Programming, Comprehensive Version plus MyProgrammingLab with Pearson eText (9th Edition)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.