"

8 Inheritance — Java Programming

8.1 Introduction

In this chapter we will learn about inheritance, one of the key characteristics of object oriented languages.  Object oriented programming languages support reuse. After we design an object to use in one program, we may find that we can reuse it in another program. We can also extend the class to add new capabilities rather than just reusing the class.

8.2  Inheritance

Inheritance is a way to add functionality to a class without changing the underlying class. A class that is inheriting is subclass ( also a child class or derived class or extended class. The class from which the subclass is derived is called a superclass (also a base class or a parent class).

Figure 8.1 Super class sub class

General form of inheritance is:

class newclass extends existingclass // newclass is child class and existing class is parent (super) class

Example

class sss extends s;  //sss  is subclass and s is superclass.

Program8.1  Program to demonstrate inheritance.

// inheritDemo.java

//click here for code

import java.io.*;

class inheritDemo

{

  public static void main (String args[])

  {

   arithmetic ar = new arithmetic ();

   System.out.println ("the variables n1 and n2 are in sumdiff b");

   System.out.println ("n1 = "+ar.n1);

   System.out.println ("n2 = "+ar.n2);

   ar.n3 = ar.mul ();

   System.out.println ("result after multiplication "+ar.n3);

   ar.n3 = ar.sum ();

   System.out.println ("result after add b "+ar.n3);

   ar.n3 = ar.diff ();

   System.out.println ("result after diff b "+ar.n3);

   ar.n3 = ar.div ();

   System.out.println ("result after div b "+ar.n3);

  }

}

class sumdiff
{
  int n1, n2;
 
 public sumdiff ()//constructor

  {

   n1 = 15;

   n2 = 10;

  }

  public int sum ()

  {

 int n3;

 n3 = n1 + n2;

 return n3;

  }




  public int diff ()

  {

 int n3;

 n3 = n1 - n2;

 return n3;

  }

}




// arithmetic inheriting from sumdiff

class arithmetic extends sumdiff

{

  int n3;

  public int mul ()

  {

 int n3;

   n3 = n1 * n2;

   return n3;

  }

  public int div ()

  {

 int n3;

 n3 = n1 / n2;

 return n3;

  }

}




/*

Output:

the variables n1 and n2 are in sumdiff b

n1 = 15

n2 = 10

result after multiplication 150

result after add b 25

result after diff b 5

result after div b 1

*/

In the above program, sumdiff is a class with two methods sum() and diff(). We defined another class arithmetic that inherited n1, n2 and sum(), diff() methods.

We added two more functions mul() and div(). Now, we can access all four methods. We need not write another constructor for arithmetic.

Java always calls the constructor of the superclass even if we include a constructor in subclass.

A class member that has been declared as private will remain private to its class.

8.3 Super class and subclass

8.3.1 Super class

Super class is the parent class from which other classes can be derived.

The this keyword refers to the parent class, that is the super class. When we override methods of a super class we replace the methods with efficient methods. Sometimes, we want to retain this super class methods and also extend their functionality.

If we override and yet require the methods of a super class we then will have to re-code the methods. But if we want to reuse existing methods of the superclass and also want to add more functionality to the existing methods, we use the keyword super. With this word we can refer the data and methods of the parent class even if they have been overridden.

The call to the super must be the first time in the constructor of the subclass.

A reference variable of a superclass can be assigned to any subclass derived from that superclass.

In a hierarchy of classes, controller are called in order of derivation, from superclass to subclass.

8.3.2 Subclass

A class that inherits from other class automatically  includes essentially all of the methods and fields of the class that it inherits from. A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass [8.1].

Program 8.2 Program to demonstrate super and child classes 
//superDemo.java
//click here for code
class candidate
{ //super class
int id;
String name;
candidate (int id, String name)
  {
this.id = id;
this.name = name;
} 
} 

class student extends candidate
{ //child class
int marks;
student (int id, String name, int marks)
  {
   super (id, name);//parent or super class constructor  
   this.marks = marks;
} 

void display ()
  {
   System.out.println (id + " " + name + " " + marks)
} 
} 

class superDemo
{
public static void main (String[]args)
  {
   student stud = new student (1001, "Ramu", 97);
   stud.display ();
}}

/* Output:

1001 Ramu 97

*/

Program 8.3. Program to demonstrate the use of the keyword super.

//x.java
//click here for code
public class x extends y
{
  int a = 1;
  int b = 2;
  public static void main (String args[])
  {
   x xobj = new x ();
  }

  public x ()
  {
   super.sum (a, b);
   super.diff (a, b);
   super.mul (a, b);
  }
}

class y
{
  public static void sum (int a, int b)
  {
   System.out.println ("sum=" + (a + b));
  }
  public void diff (int a, int b)
  {
   System.out.println ("diff=" + (a - b));
  }
  public static void mul (int a, int b)
  {
   System.out.println ("mul=" + (a * b));
  }
}

/* Output:
sum=3
diff=-1
mul=2
*/

8.4 Multiple inheritance

If we want to create a class that inherits from multiple classes, then this is called multiple inheritance. Java does not support multiple inheritance. As an alternative to multiple inheritance, Java provides interface, We will learn about interfaces in the next chapters.

Program 8.4 Program to demonstrate function inheritance.

//myclass.java
//click here for code
class p1
{
  p1( ){
  System.out.println("inside p1");
 }
}

class p2 extends p1
{
p2(){
System.out.println("inside p2");
}
}

class p3 extends p2
{
p3(){
System.out.println("inside p3");
}
}

class myClass
{
public static void main(String args[])
{
 p3 c =new p3();
}
}

/*
Output:
inside p1
inside p2
inside p3
*/

Program 8.5 Program to define a super class student, which will be used in the next program 8.6. Just compile this program. Do not execute.

//istudent.java

//click here for code
import java.io.*;
import java.util.*;
public class istudent
{
String name;
int regdno;

public istudent()
{
name=" ";
regdno=0;
}

public void getdata()
{
try{
DataInputStream in=new DataInputStream(System.in);
System.out.println("enter student name");
name=in.readLine();
System.out.println("enter register number");
String k=in.readLine();
regdno=Integer.parseInt(k);
}
catch(Exception e)
{
System.out.println("I/O error"+e);
System.exit(1);
}
}
}

Program 8.6. Program that inherits from istudent class defined above. Compile the above program 8.5 and run this program.

//year1.java

//Click here for code

import java.io.*;
import java.util.*;
public class year1 extends istudent
{
int a[]=new int[10];
float per;
public year1()
{
super();
per=0;
}

public void getdata(int n)
{
int sum1=0,x=0;
getdata();
try{
DataInputStream in;
in=new DataInputStream(System.in);
System.out.println("enter the marks");
sum1=0;
String k;
for(int i=0;i<n;i++)
{
k=in.readLine();
x=Integer.parseInt(k);
a[i]=x;
sum1=sum1+a[i];
}
per=(float) (sum1/n);
}
catch(Exception e)
{
System.out.println("I/O error"+e);
System.exit(1);
}
}
public static void main(String args[])
{
int m=0,n=0;
year1 first[]=new year1[10];
try
{
DataInputStream in;
in=new DataInputStream(System.in);
System.out.println("enter the number of subjects");
String s=in.readLine();
n=Integer.parseInt(s);
System.out.println("enter the number of students");
s=in.readLine();
m=Integer.parseInt(s);
}
catch(Exception e)
{
System.out.println("I/O error"+e);
System.exit(1);
}
for(int i=0;i<m;i++)
{
first[i]=new year1();
first[i].getdata(n);
}

for(int i=0;i<m;i++)
System.out.println(first[i].name+" "+first[i].regdno+" "+first[i].per);
}
}

/* 
Output:
enter the number of subjects
5
enter the number of students
4
enter student name
Amar
enter register number
10
enter the marks
70
78
67
80
90
enter student name
Sunil
enter register number
11
enter the marks
71
69
75
56
89
enter student name
Badri
enter register number
12
enter the marks
72
70
67
59
92
enter student name
Chand
enter register number
14
enter the marks
70
71
89
56
78
Amar 10 77.0
Sunil 11 72.0
Badri 12 72.0
Chand 14 72.0
*/

8.5 Overriding methods

Some times we may want to modify the functionality of an existing method in a given super class. We override the method that is, we change the functionality of a subclass. We do overriding by creating a new method with the same name as the overridden method. When an overridden method is called from a subclass, it will always refer to the version of that method defined by the subclass. The previous version of the method defined by the super class will be hidden.

Program 8.7. Program to demonstrate overriding.

//overRide.java
//click here for code
class p1
{
  int i, j;
  p1 (int a, int b)
  {
    i = a;
    j = b;
  }
  //method show() prints i and java
  void show(){
      System.out.println("i="+i+"j="+j);
  }
  }

class p2 extends p1
{
    int k;
    p2(int a, int b, int c){
        super(a,b);
        k=c;
    }

    //the following show() function overrides show() of p1
    void show(){
        System.out.println("k:="+k);
    }
}

class overRide{
    public static void main(String args[]){
        p2 ex=new p2(1,2,3);
        ex.show(); //this execures p2 show()
    }
}

/*
Output
k:=3
*/
If we want to execute p1’s show(), modify above code with super.show().

8.6 Difference between overloading and overriding

Method overriding happens only when method names and number of parameters and types match. That is the method signatures should match. Otherwise overloading happens.

8.7 Dynamic Method dispatch

Dynamic method dispatch is the mechanism by which a call to an overridden function is resolved at runtime, rather than compile time. Dynamic Method Dispatch is important because this is how Java implements run time polymorphism. If a super class contains a method that is overridden by a subclass, then when different types of objects are referred to through a superclass reference variable, different versions of the method are executed.

Program 8.8 Program to demonstrate Dynamic Method dispatch

//dmd.java
//click here for code
class p1
{
  void override ()
  {
 System.out.println ("inside p1");
  }
}

class p2 extends p1{
    void override(){
        System.out.println("inside p2");
    }
}

class p3 extends p2{
    void override(){
        System.out.println("inside p3");
    }
}

class dmd{
        public static void main(String args[]){
        p1 a=new p1();
        p2 b=new p2();
        p3 c=new p3();
        p1 r;
        r=a;
        r.override();
        r=b;
        r.override();
        r=c;
        r.override();
    }
}

/* Output:
inside p1
inside p2
inside p3
*/

8.8 Abstract class

Sometimes we may want to create a superclass that only defines a generalised form that will be shared by all it’s subclasses, leaving it to each subclass to fill in the details. The real implementations are done in the respective subclasses. Any class which has abstract method definitions, should be declared as an abstract class.
Program 8.9 Program to demonstrate abstract class 
//abstractDemo.java

//Click here for code
abstract class p1{ //p1 is an abstract class
abstract void show(); //show() is an unimplemented function
void show2(){
//show2() is an implemented function
System.out.println("in class p1 show2()");
}
}
class p2 extends p1{ //p2 is subclass of p1
void show() { //show which was unimplemented in p1 is implemented here
System.out.println("in class p2 show()");
}
}
class abstractDemo{
public static void main(String args[]){
p2 x=new p2();
x.show();
x.show2();
}
}

/* Output:
in class p2 show()
in class p1 show2()
*/

8.9 Preventing Overriding and inheritance

The keyword final can be used for

  1. Create the equivalent of a named constant
  2. Prevent overriding
  3. Prevent inheritance

Methods declared as final cannot be overridden.

Program 8.10 Program to prevent overriding
 
//Program 8.10 Program to prevent overriding
//preventOverride.java
class p1{
final void show(){
System.out.println("This is final show()");
}
}

class p2 extends p1{
//we cannot override show()
void show(){
System.out.println("This is invalid");
}
}

class preventOverride{
public static void main(String args[]){
p2 x=new p2();
x.show();
}
}

/*
Output:
preventOverride.java:11: error: show() in p2 cannot override show() in p1
void show(){
^
overridden method is final
1 error

*/
Program 8.11 Program to prevent inheritance
//overrideInheritance.java
//click here for code
final class p1{ //place keyword final before class 
final void show(){
System.out.println("This is final class p1 show()");
}
}

class p2 extends p1{
//this is not valid
}

class preventInheritance{
public static void main(String args[]){
p2 x=new p2();
x.show();
}
}

/*
preventInheritance.java:9: error: cannot inherit from final p1
class p2 extends p1{
^
1 error
*/

8.10 Object class

Object is the super class of all classes. This means that a reference variable of type Object can reference variable of the Object can refer to an object of any class.

Some of the methods defined in Object are

Object clone() 

Creates a new object that is same as the object being cloned.

boolean equals(Object objectname)

Determines whether one object equals other

void finalize()

Called before an unused object is recycled.

Class getClass()

Obtains the class of an object at runtime.

String to String()

returns a string that describes the object.

8.11 The Class class

Java maintains RTTI( Run Time Type Identification) which keeps track of the class to which each object belongs to. This ensures that the current methods are selected at runtime.

The class that holds this information is called Class.

The getClass() method of the Object returns an instance of this class.

8.12 Summary

In this chapter you learned inheritance, overriding, the super classes and about Object class.

Media Attributions

  • 8.1 super class sub class

License

Icon for the Creative Commons Attribution-ShareAlike 4.0 International License

Java Programming Copyright © by Valli Kumari Vatsavayi and KBS Phanindra Varma is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License, except where otherwise noted.