Sage-Code Laboratory
index<--

Java Inheritance

In the Java, classes can be derived from other classes. This is called inheritance. A class that is derived from another class is called a subclass. The parent class is called superclass. A subclass inherit the fields and the methods of the parent class.

Inheritance is one of fundamental features of Object Oriented programming. It is a powerful method to reuse code in a comprehensive manner. Once you learn this concept in Java you will be able to use this knowledge to learn other OOP Languages more easily.

Object is a Class?

Yes, there is a special class that is called "Object". This is the root class, and this is the only class that does not have a superclass. All other classes defined in Java are descended from the Object class.

Single Inheritance

Every class has one and only one direct superclass. In the absence of any other explicit superclass, a class is implicitly derived from Object. This model is called single inheritance. Notice that other languages like C++ and Python can use multiple inheritance model.

Inheritance

Java Class Hierarchy

Syntax:

We declare a subclass similar to a class in addition we specify the superclass using keyword: "extends". This is the idea to memorize: One subclass can extends a superclass like in this syntax pattern:

//define a demo standard class
public class ParentClass {
  ...
};
//define a subclass of ParentClass
public class ChildClass extends ParentClass {
  ...
};
Warning: There are classes that can not be extended. These classes are called: final classes. A class that is declared final cannot be subclassed. This is useful, for example, to create immutable classes like the String class.

Read next: Abstraction