Inheritance in Java

Inheritance in Java


Inheritance In Java Notes

Java Inheritance

This mechanism of deriving a new class from existing/old class is called “inheritance”.

The old class is known as “base” class, “super” class or “parent” class”; and the new class is known as “sub” class, “derived” class, or “child” class. The inheritance allows subclasses to inherit all properties (variables and methods) of their parent classes.

The different forms of inheritance are:

  1. Single inheritance (only one super class)
  2. Multiple inheritance (several super classes)
  3. Hierarchical inheritance (one super class, many sub classes)
  4. Multi-Level inheritance (derived from a derived class)
  5. Hybrid inheritance (more than two types)

A subclass/child class is defined as follows:

class SubClassName extends SuperClassName
{
   fields declaration;
   methods declaration;
}

The keyword “extends” signifies that the properties of super class are extended to the subclass. That means, subclass contains its own members as well of those of the super class. This kind of situation occurs when we want to enhance properties of existing class without actually modifying it.

Important Points

  • Declaring class with final modifier prevents it being extended or subclassed. Defined constructor can invoke base class constructor with super.
  • Subclasses defining variables with the same name as those in the superclass, shadow them.
  • Derived/sub classes defining methods with same name, return type and arguments as those in the parent/super class, override their parents methods:
    
    class A {
       int j = 1;
       int f( ) { return j; }
    }
    
    class B extends A {
       int j = 2;
       int f( ) { return j; }
    }
    
    class override_test {
        public static void main(String args[ ] ) {
    
         B b = new B();
         System.out.println(b.j); / / refers to B.j prints 2
         System.out.println(b.f()); / / refers to B.f prints 2
         A a = (A) b;
         System.out.println(a.j); / / now refers to a.j prints 1
         System.out.println(a.f()); / / overridden method still refers to B.f() prints 2 !
    
        }
    }
    
    
  • Inheritance promotes reusability by supporting the creation of new classes from existing classes.
  • Child class constructor can be directed to invoke selected constructor from parent using super keyword.
  • Variables and Methods from parent classes can be overridden by redefining them in derived classes.