Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

INHERITANCE

Concept
i) Inheritance is based on the idea of reusability.
ii) This means that the features of an existing class are reused and new features are added to
it.
iii) The existing class undergoes no modifications (i.e. it remains unchanged), it is just
extended to form a new class.

Types of the inheritance


Single level inheritance
Hierarchical inheritance
Multilevel inheritance
Basics
Inheritance is the technique of creating a new class by building upon an existing class
definition.The existing
class is referred to as parent or super or base class, and the new class is called a child or sub or
derived class.
The Object class:
The Object class defined in java.lang package specifies the topmost (i.e. root) class of the Java
class hierarchy tree. In the absence of any other explicit superclass, every class is implicitly a
subclass of the Object class.

Sub Class Specification (Syntax):


class <sub–classname> extends <base-class>
{
//…. subclass members
}// here, extends is a keyword used in Java that sets a relationship between a parent class
and a child class.
class Rectangle // super class
{
int len, bdt ;
//…. other members of Rectangle
}
class Room extends Rectangle // sub class
{
int hgt ;
//…. other members of Room
}
// Single inheritance with factorial computation
class Base { // super class
int ctr ;
void factorial( ) {
int i, fact = 1 ;
for(i = ctr ; i > 0 ; i– –) fact = i ;
System.out.println(“Factorial = “ +fact) ;
}
} // end of Base class
class Derv extends Base { // subclass
void setCtr(int n) {
ctr = n ;
}
}
class Test {
public static void main(String args[ ]) throws Exception
{
Derv od = new Derv( ) ; // derived class object
od.setCtr(5) ;
od.factorial( ) ; // derv. class accesses members of base class
}
}
Inheritance and Member Accessibility
The accessibility of base class members inside a sub class depends on the fact that whether the
i) subclass belongs to same base class’s package.
ii) subclass belongs to some other package.

Derived Class Visibility


Base Class Visibility
Within base class’s package Outside base class’s package

private Not inherited Not inherited

protected Yes Yes

public Yes Yes

default (no modifier) Yes No

Visibility of Class Members


Note:
Private members are neither accessible nor inheritable outside the class. However, inherited
public or protected
methods of the parent class can be used for accessing the private fields by the subclass.
ii) The protected visibility provides the best encapsulation while still permitting inheritance.
iii) A subclass inherits all of the public and protected members of its parent, no matter what
package the subclass is in.
iv) If the subclass is in the same package as its parent, it also inherits the package private
(default) members of the parent.
v) The subclass does not inherit the constructors from its base class.

// Single inheritance and Member Accessibility


class Rectangle { // superclass
private int width ;
protected int depth ;
int getWidth( ) { // default access
return width ;
}
protected void setWidth(int w) { // protected access
width = w ;
}
} // end of super class
class Box extends Rectangle { // subclass
private int height ;
public void setHeight(int h) { // public access
height = h ;
}
int boxArea( ) {
int ar, w ;
// ar = width  depth ; Error: width has private access
w = getWidth( ) ; // inherited default method accesses private field
ar = w  depth ; // accessing protected inherited member
return ar ;
}
int boxVol( ) {
int v = boxArea( )  height ;
return v ;
}
} // end of sub class
class Test
{
public static void main(String args[ ]) throws Exception
{
Box a = new Box( ) ; // subclass object
a.setWidth(15) ; // invoking protected inherited method to access private field
a.depth = 10 ; // accessing inherited protected field
a.setHeight(12) ;
System.out.println(“\nArea = “ +a.boxArea( )) ; // Area = 150
System.out.println(“\nVolume = “ +a.boxVol( )) ; // Volume = 1800
}
}
Sub Class Constructors
A subclass constructor is used to initialize the instance variables of both the subclass and the
super class. The subclass constructor invokes the constructor of the super class, either
implicitly or by using the keyword super.
Syntax:
super( ) ; // Invoking default parent constructor
or
super(parameter–list); // Invoking parameterized parent constructor
Note:-
i) If the superclass definition contains a parameterized constructor then, the subclass must
have a parameterized constructor explicitly invoking a super(…).
ii) Explicit invocation of a superclass constructor must be the first line in the subclass
constructor.

// Using super to call superclass constructor


class B { // superclass
private int a ;
private double b ;
B(int a, double b ) {
System.out.println(“Base class constructor called”) ;
this.a = a ; this.b = b ;
}
//…..
}
class D extends B { // subclass
private int x ;
private double y ;
D(int x, double y, int m, double n) {
super(m, n) ; // invoking superclass constructor
System.out.println(“\nSub class constructor called”);
this.x = x ; this.y = y ;
}
//……
}
class Test {
public static void main(String args[ ]) throws Exception
{
D od = new D(3, 7.5, 4, 9.25) ; // subclass object
//……
}
}
Output:
Base class constructor called
Sub class constructor called

Order of Invocation:
When a subclass is instantiated, the object will begin with an invocation of the constructor in
the base class and initialize downwards through constructors in each subclass till it reaches
the final subclass constructor.

Instance Variable Hiding


If a subclass declares a variable with the same name as one in the superclass, then the
subclass variable hides the
inherited superclass variable.
The hidden variable / field can be accessed using the keyword super as:
super . variable–name

// Using super to refer an inherited hidden field


class B { // superclass
int i ;
}
class D extends B { // subclass
int i ; // hides field ‘ i ’ of base class
private double y ;
D(int a, int b) {
super.i = a ; // refers to inherited hidden field ‘ i ’
this.i = b ;
}
void show( ) {
System.out.println(“Hidden field: “ +super.i) ;
System.out.println(“Visible field: “ +i) ;
}
} // end of class D
class Test {
public static void main(String args[ ]) throws Exception
{
D od = new D(10, 20) ; // subclass object
od.show( );
}
}
Output:
Hidden field: 10
Visible field: 20

Method Overriding
It is a concept which occurs when an instance method in a subclass hides or overrides an
inherited method of the superclass due to similar declarations.
Overridden methods are methods that are redefined within an inherited class or subclass.
An overridden super class method can be invoked in a subclass using the keyword super as:
super . overriddenMethod( ) ;

// Using super to invoke an overridden method


class B { // super class
private int x ;
B(int x) {
this.x = x ;
}
void display( ) {
System.out.println(“Super x = “ +x) ;
}
} // end of super class B
class D extends B { // subclass
int y ;
D(int x, int y) {
super(x) ; // invoking parent constructor
this.y = y ;
}
void display( ) // overriding method redefinition
{
super.display( ) ; // invoking hidden parent method
System.out.println(“Sub y = “ +y) ;
}
}
class Test {
public static void main(String args[ ]) throws Exception
{
D od = new D(10, 20) ;
od.display( ) ; // invokes display( ) of D
}
}
Output:
Super x = 10
Sub y = 20

Use of keyword super :


It may used to either access a superclass member (method or instance variable) or invoke a
parent class’s constructor.

Abstract Classes
i) An abstract class defines a structure of given abstraction without any implementation.
ii) In Java, an abstract class is a special type of superclass that is specified by using the
abstract keyword as:
abstract class < classname >
{ ……. }
iii) Abstract classes cannot be instantiated, as they are defined solely for the purpose of
extension (inheritance) by other classes.

Abstract Methods
i) It is an overridden method which is declared with the abstract modifier in an abstract
super class, but implemented
specifically in a subclass.
Declaration Syntax:
abstract type <methodname> ([ parameter–list ]) ;
Polymorphism: It is the capability of an action or method to do different things based on the
object it is acting upon.
Compile Time Run Time

Also called early or static Also called late or dynamic


binding. binding.
It is achieved using method It is achieved using method
overloading. overriding.
It is a mechanism by which the It is a mechanism by which the
call to an overloaded method call to an overridden method
is resolved by the compiler at is resolved by the JVM at the
the compile time. run time.
// Dynamic binding using an overridden method
abstract class Shape { / / abstract super class
double ar ;
abstract void area( ) ; // abstract method declaration
}
class Circle extends Shape { // subclass
double radius ;
Circle(double r) {
radius = r ;
}
public void area( ) { // abstract method definition version 1
ar = 3.14  radius  radius ;
System.out.println(“Circle area = “ +ar) ;
}
}
class Triangle extends Shape { // subclass
double base, height ;
Triangle(double b, double h) {
base = b ; height = h ;
}
public void area( ) { // abstract method definition version 2
ar = base  height / 2 ;
System.out.println(“Triangle area = “ +ar) ;
}
}
class PolyTest {
public static void main(String args[ ]) throws Exception {
Shape s ; // abstract superclass reference variable
s = new Circle(2.0) ; // s refers to Circle object
s.area( ) ; // invokes area( ) of Circle
s = new Triangle(2.0, 5.0) ; // s refers to Triangle object
s.area( ) ; // invokes area( ) of Triangle
} // end of main
} // end of main class
Output: Circle area = 12.56
Triangle area = 5.0
The type of subclass object referred to by the superclass reference variable at run time
dynamically determines the
execution of the correct version of the abstract method, thus implementing Java’s approach to
subclass polymorphism.

Interface (PROGRAM OF INTERFACE IS NOT IN THE SYLLABUS OF ISC 2020-21)


i) An interface in Java is a collection of final constants and abstract methods. it is
protocol of behaviour
for its derived class
ii) Interfaces are syntactically similar to classes, but they lack instance variables and their
methods specify only their signatures, not their code. For e.g.
interface Area { // An interface definition
final double pi = 3.14 ;
abstact double calcArea(double x, double y) ;
}
iii) The implements clause in a class definition implements the interface. For e.g.
// An interface implementation
class Rectangle implements Area {
public double calcArea(double x, double y) {
return (x  y) ;
}
}
iv) Interfaces are used like a super class whose properties can be implemented by one or
more classes.

Class Vs Interface:
i) A class consists of instance variables and methods definitions while an interface consists
of final constants and method declarations.
ii) A class can be instantiated using the new operator while an interface cannot be
instantiated as they are abstract in nature.
Abstract Class Vs Interface:
i) An abstract class is defined using abstract keyword while an interface is specified using
keyword interface.
ii) An abstract class is implemented using extends keyword while an interface is
implemented using keyword

You might also like