Inheritance is one of the three foundational principles of object oriented programming (abstraction, polymorphism and inheritance) because it allows the creation of hierarchical classifications. Using inheritance,  we can generate class that defines traits common to set of related classes. This class can then be inherited by other more specific classes each adding those things that are unique to it.

Reusability is one of the most important aspects of OOP paradigm. It is always nice if we could reuse something that already exists rather than creating the same all over again. Java supports this concept. Java classes can be reused in several ways. This is basically done be creating new classes, reusing the properties of existing ones. The mechanism of deriving a new class from an old class is called inheritance. The old class is known as the super class and the new one class is called the subclass

The inheritance allows subclasses to inherit all the variables and methods of their parent classes. Inheritance may take different forms:

  • Single inheritance (only one super class).
  • Hierarchical Inheritance (one super class, many subclasses).
  • Multilevel inheritance (Derived from a derived class).

Defining a Subclass

A subclass is defined as follows:

class subclassname extends superclassname {

               Variables declaration;

               Methods declaration;

}

The keyword extends signifies that the properties of the superclassname are extended to the subclassname. The subclass will now contain its own variables and methods as well those of the superclass. This kind of situation occurs when we want to add some more properties to an existing class without actually modifying it.

Application of single inheriatnce

class Room

{

               int length;

               int breadth;

               Room(int x,int y)

               {

                              length = x;

                              breadth =y;

               }

               int area()

               {

                              return (length*breadth);

               }

}

class BedRoom extends Room

{

               int height;

               BedRoom(int x, int y, int z)

               {

                              super(x,y);

                              height = z;

               }

               int volume()

               {

                              return (length*breadth*height);

               }

}




class InherTest

{

               public static void main(String args[])

               {

                              BedRoom room1 = new BedRoom(14,12,10);

                              int area1 = room1.volume();

                              int volume1 = room1.volume();

                              System.out.println("Area = "+area1);

                              System.out.println("Volume = "+volume1);

               }

}

 

Subclass Constructor

A subclass constructor is used to construct the instance variables of both the subclass and the superclass. The subclass constructor uses the keyword super to invoke the constructor method of the superclass. The keyword super is used is used subject to the following conditions.

  • Super may only be used within a subclass constructor.
  • The call to superclass constructor must appear as the first statement within the subclass constructor.
  • The call to superclass constructor must appear as the first statement within the subclass constructor.
  • The parameters in the super call must match the order and type of the instance variable declared in the superclass.

Multilevel Inheritance

A common requirement in object oriented programming is the use of a derived class as a super class. Java supports this concept and uses it extensively in building its class library. This concept allows us to build a chain of classes shown below:

The class A serves as base class for the derived class B which in turn serves as a base class for the derived class C. The chain ABC is known as inheritance path.

A derived class with multilevel base is declared as follows:

class A

{

               ……………….

               ……………….

}

class B extends A

{

               ………………

               ………………

}

class C extends B

{

               …………..

               …………..

}

The process may be extended to any number of levels. The class C can inherit the members of both A and B.

Hierarchical Inheritance

Another interesting application of inheritance is to use it as a support to the hierarchical design of a program. Many programming problems can be cast into a hierarchy where certain features of one level are shared by many others below the level.

The following program demonstrates hierarchical inheritance

class Box{

    double length;

    double breadth;

    double height;

    Box(){

        length=breadth=height=0;

    }

    Box(double l){

        length =breadth=height=l;

    }

    Box(double l, double b, double h){

        length =l;

        breadth =b;

        height =h;

    }

    double getVolume(){

        return length*breadth*height;

    }

}

class BoxWt extends Box{

    double weight;

    BoxWt(){

        super();

        weight=0;

    }

    BoxWt(double l, double w){

        super(l);

        weight=w;

    }

    BoxWt(double l, double b, double h, double w){

        super(l,b,h);

        weight=w;

    }

    double getWeight(){

        return weight;

    }

}

class Shipment extends BoxWt{

    double cost;

    Shipment(){

        super();

    }

    Shipment(double l, double w, double c){

        super(l,w);

        cost = c;

    }

    Shipment(double l, double b, double h,double w, double c){

        super(l,w,h,w);

        cost = c;

    }

    double getCost(){

        return cost;

    }

}

class Inheritance {

    public static void main(String[] args) {

        Shipment s = new Shipment(10,8,5,2,50);

        System.out.println("The volume of box = "+s.getVolume());

        System.out.println("The weight of box = "+s.getWeight());

        System.out.println("The cost of box = "+s.getCost());

    }

}

 

The output of the above program is:

The volume of box = 100.0

The weight of box = 2.0

The cost of box = 50.0

Overriding Methods  

It is seen that a method in a superclass is inherited by its subclass and is used by the objects created by the subclass. Method inheritance enables us to define and use methods repeatedly in subclasses without having to define the methods again in subclass.

However, there may be occasions when we want an object to respond to the same method but have different behavior when that method is called. This means that we should override the method defined in the superclass. This is possible by defining a method in the subclass that has the same name, same arguments and same type as a method in the superclass. Then, when that method is called, the method in the subclass is invoked and executed instead of the one in the superclass. This is known as overriding.

The following program illustrates program that shows method overriding.

class Super

{

               int x;

               Super(int x)

               {

                              this.x = x;

               }

               void display()

               {

                              System.out.println("Super x = "+x);

               }

}

class Sub extends Super

{

               int y;

               Sub(int x,int y)

               {

                              super(x);

                              this.y = y;

               }

               void display()

               {

                              System.out.println("Super x = "+x);

                              System.out.println("Sub y = "+y);

               }

}

class OverrideTest

{

               public static void main(String args[])

               {

                              Sub s1 = new Sub(100,200);

                              s1.display();

               }

}

 

The output of the above program is:

Super x = 100

Sub y  = 200

Invoking the Overridden method

Using super keyword

If you wish to access the superclass version of an overridden method you can do so by using super. For example consider an above example:

class A{

int  I,j;

public A(int a ,int b){

i = a;

j = b;

}

public void show(){

System.out.println("I and j"+i+ " , "+j):

}

}

class B extends A{

int k;

public B(int a, int b, int c){

super(a,b);

k = c;

}

void show(){

super.show();

System.out.println ("k:"+k);

}

}

class Override{

public static void main(String[] args){

B ob1 = new B(1,2,3);

ob1.show();

}

}

 

The output will be:

I and j : 1,2

k : 3

 

Dynamic Method Dispatch

Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time. Dynamic method dispatch is important because this is how Java implements runtime polymorphism. Consider an example that demonstrates the dynamic method dispatch. When an overridden method is called through a superclass reference, Java determines which version of that method to execute based upon the type of the object being referred to at the time of the call occurs. Thus, this determination is made at run time. Therefore, if a superclass contains a method that is overridden by a subclass, then when different types of objects are referred to through superclass reference variable, different versions of the method are executed. Here is an example that illustrates dynamic method dispatch.

class First{

    public void callme(){

        System.out.println("Inside First's callme method");

    }

}

class Second extends First{

    public void callme(){

        System.out.println("Inside Second's callme method");

    }

}

class Third extends Second{

    public void callme(){

        System.out.println("Inside Third's callme method");

    }

}

public class DynamicDispatch {

    public static void main(String[] args) {

        First f = new First();

        Second s = new Second();

        Third t = new Third();

        First r;

        r = f;

        r.callme();

        r  =s;

        r.callme();

        r = t;

        r.callme();       

    }   

}

 

The output of the above program is:

run:

Inside First’s callme method

Inside Second’s callme method

Inside Third’s callme method

Use of final keyword

In Java keyword final has three uses

  • Using final to create the equivalent of the named constants: Variable can be declared as a final to prevent its contents from being modified that is similar as const in C and C++/C# etc.

final double PI = 3.1416

  • Using final to prevent Method Overriding: The methods declared as a final can’t be overridden. The final keyword can be used as modifier at the starting of the method declaration to disallow it being overridden. Example:
class A{

final void meth(){ System.out.println("This is a final method");}

}

class B extends A{

void meth(){

System.out.println("Illegal");

}

}

 

Here the method meth () is declared as final and it can’t be overridden in B. If we attempt to do so a computer generates the error.

  • Using final to prevent Inheritance: Some time we may like to prevent the class being further sub classed for security purpose. A class that can’t be sub classed is called a final class. This is achieved in Java using the keyword final: Example

               final class A{

                                             ……….

                                             ……….

                                  }

               class B extends A{               //Error : can’t subclass A

                                             ……….

                                             ……….

                                             }

 

Abstract Methods and Classes

If we declare a class as abstract, then it is necessary for you to subclass it so as to instantiate the object of that class. That is we cannot instantiate object of abstract class and it contains its subclass. The keyword abstract is used to create a class as an abstract class and it contains before it can be used. We can declare the method as an abstract using abstract keyword and without the method definition or it ends with semicolon. If we declare some class as abstract then we must declare its class as abstract. The abstract methods of an abstract class must be defined in its subclass.

Abstract class

Any class that contains one or more abstract methods must also be declared abstract by using the keyword abstract at the beginning of the definition and such classes are called abstract class.

  • There is no object of abstract class and it is defined for subclass.
  • Abstract class cannot be directly instantiated with the new operator.
  • We cannot declare abstract constructor or abstract static methods.
  • Any subclass of abstract class must either implement all of the abstract methods in the super class, or be itself declared abstract.
  • Abstract class may contain concrete methods(methods with definitions)

Defining abstract class and the abstract methods

abstract class Figure{

    double dim1;

    double dim2;

    public Figure(double a,double b){

        dim1 = a;

        dim2 = b;

    }

    public abstract double area();       

 }

class Rectangle extends Figure{

    public Rectangle(double a,double b){

        super(a,b);

    }

    public double area(){

        System.out.println("Inside Area for Reactagle ");

        return dim1*dim2;

    }

}

class Triangle extends Figure{

    public Triangle(double a, double b){

        super(a,b);

    }

        public double area(){

            System.out.println("Inside Area for Triangle");

            return dim1*dim2/2;

        }

    }

public class AbstractAreas {

    public static void main(String[] args) {

        Rectangle r = new Rectangle(9,4);

        Triangle t = new Triangle(9,5);

        Figure fig;

        fig = r;

        System.out.println("Area is "+fig.area());

        fig = r;

        System.out.println("Area is "+fig.area());

    }   

}

 

 

The Object Class

There is one special class, Object, defined by Java. All other classes are subclasses of Object. That is, Object is a superclass of all other classes. This means that a reference variable of type Object can refer to an object of any other class. Also, since arrays are implemented as classes, a variable of type Object can also refer to any array.

Object defines the following methods, which means that they are available in every object.

Method Purpose
Object clone() Creates a new Object that is the same as the new object being cloned
Boolean equals(Object object) Determines whether one object is equal to another
Void finalize() Called before an unused object is recycled
Class getClass() Obtains the class of an object at run time
Int hashCode() Returns the hash code associated with the invoked object
Void notify() Resumes the execution  of a thread waiting on the invoking object
Void notifyAll() Resumes execution of all threads waiting on the invoking object
String toString() Returns a string that describes the object
Void wait()

Void wait(long milliseconds)

Void wait(long millisecond, int nanoseconds)

Waits on another thread of execution

Use of Final keyword

In Java keyword final has three uses

  • Using final to create the equivalent of the named constants: Variable can be declared as a final to prevent its contents from being modified that is similar as const in C and C++/C# etc.

final double PI = 3.1416

  • Using final to prevent Method Overriding: The methods declared as a final can’t be overridden. The final keyword can be used as modifier at the starting of the method declaration to disallow it being overridden. Example:
class A{

final void meth(){ System.out.println("This is a final method");}

}

class B extends A{

void meth(){

System.out.println ("Illegal");

}

}

 

Here the method meth() is declared as final and it can’t be overridden in B. If we attempt to do so a computer generates the error.

  • Using final to prevent Inheritance: Some time we may like to prevent the class being further subclassed for security purpose. A class that can’t be sub classed is called a final class. This is achieved in Java using the keyword final: Example

               final class A{

                                             ……….

                                             ……….

                                  }

               class B extends A{               //Error : can’t subclass A

                                             ……….

                                             ……….

                                             }

 


Didn't Find Any Subjects/Contents?

Click on the contribute button to contribute subjects materials on Study Notes Nepal.

Contribute

Leave a Reply

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


Join Our Facebook Community Group

Study Notes Nepal