You are on page 1of 10

Ch11 Inheritance,Abstract Classes and Interfaces

Constructor
A constructor is a special method which is used to create objects of the class.Constructors initialize data
members at the time of creation.The constructor has the same name as the class itself and does not have
return type,not even void.Types of Constructors Default Constructor, Non Parameterized Constructor and
Parameterized Constructor.
No Arguments or Non
ParameterizedConstructor

Parameterized Constructor

package eg01;
public class eg01
{
public static void main(String args[])
{
book mybook=new book();
mybook.bookName="Meat!";
mybook.authorName="Brottman";
mybook.price=40;
mybook.display();
}
}
class book
{
String bookName;
String authorName;
double price;
public book()
{
bookName=B;
authorName=A;
price=0;
}
void display()
{
System.out.println("Book
Name :"+bookName);
System.out.println("Author
Name :"+authorName);
System.out.println("Price
}
}

package eg01;
public class eg01
{
public static void main(String args[])
{
book mybook=new
book(Meat!,Brottman,40);
mybook.display();
}
}

class book
{
String bookName;
String authorName;
double price;
public book(String bName,String
aName,double p)
{
bookName=bName;
authorName=aName;
price=p;
}
void display()
{
System.out.println("Book
Name :"+bookName);
System.out.println("Author
Name :"+authorName);
System.out.println("Price
:"+price);
}
}

If this is
not
present
Java will
provide a
default

:"+price);

Default Constructor
Even if we dont provide any constructors for a Class, we can still call a Nonparamterized Constructor to
create objects of that Class. This is possible Java provides all classes with a Default Constructor which does
nothing. eg public book(){}
Note:When we provide a Constructor for a Class, this Constructor will override the Default Constructor.
Differences between a Constructor and an Ordinary Method or What are the special features of
constructors?
No
Constructor
Ordinary Method

1
2
3
4

Constructor has same name as class name.


Constructor does not have return type, not
even void.
Constructors are used to create objects of
classes.
Constructors of super classes are not
inherited by subclasses.

Method does not have same name as class name


Method always has a specific return type or void.
Methods are not used to create objects of classes.
Methods of super classes are inherited by child
classes.

Inheritance
Inheritance is a powerful feature of Object Oriented programming which allows new classes to be derived
from existing ones.The child class inherits all the data members and methods of the parent class and may
contain new additionally data members and methods. Inheritance is implemented in Java using the
extends keyword.
Eg class c2 extends c1
where c1 is the parent class and c2 is the child class.
No

Super class or Parent class or Base class


or Supertype

Sub class or Child class or Derived class or


Extended class or Subtype

The class from which a child class is derived is


known as super class.
The super class stands for a general concept
which applies to all sub classes.
The super class will not have the new
additional data members and methods of the
child class.

The class which is derived from the parent class is


known as sub class.
The sub class stands for a specific concept and is a
special case of the super class.
The sub class inherits all the data members and
methods of the super class may additionally
contain new data members and methods.

2
3

Inheritance Example
Book
Referen
ce

Novel

*Note:All the classes below are placed in the same package eg05;
class book
Super Class
{
String bookName;
String authorName;
double price;
public book(String bName,String aName,double
p)
{
bookName=bName;
authorName=aName;
price=p;
}
void display()
{
System.out.println("Book
Name :"+bookName);
System.out.println("Author
Name :"+authorName);

package eg05;
public class eg05
Main Class
{
public static void main(String args[])
{
novel n1=new novel("Dark Hollow",
"Brian Keane",50,"Horror",7);
n1.displayNovel();
reference r1= new reference("The Werewolf
Book",
"Brad Steiger",120,"Lycanthropy",1999);
r1.displayReference();
}
}

System.out.println("Price

:"+price);

}
}
class novel extends book
{
Sub Class1
String category;
int rating;
public novel(String bName,String
aName,double p,
String cat,int rat)
{
super(bName,aName,p);
Call to Super
category=cat;
Class
rating=rat;
}
public void displayNovel()
{
Call to Super
super.display();
Class Method
System.out.println("Category :"+category);
System.out.println("Rating :"+rating);
}
}
Note: Call to super classs constructor must be the first

class reference extends book


{
Sub Class2
String topic;
int yearPublished;
public reference(String bName,String aName,
double p,String top,int y)
{
super(bName,aName,p);
Call to Super
topic=top;
Class
yearPublished=y;
}
public void displayReference()
{
Call to Super
super.display();
Class Method
System.out.println("Topic
:"+topic);
System.out.println("Published
in:"+yearPublished);
}
}
statement in the sub classs constructor.

The Need for Inheritance or Advantages of Inheritance


or Why was the concept of inheritance introduced in Object Oriented Languages?
1) Capability to express Inheritance Relationship which models the Real World
The Inheritance Relationship allows java classes to model the real world.Consider the example of Book
which is a Super class.From it are derived Child Classes Novel and Biography.Novel is further subclassed
into Thriller. From this hierarchy we know that a Thriller is always a Novel and Novels and Biographies are
always books.

2) Reusability of code
Inheritance allows reusability of code ie When we need to create a class similar to an already existing
class, there is no need to start from scratch.We can simply derive a child class from the existing class and
add new data members and methods.
3) Transitive Nature of Inheritance reduces Maintenance
Consider the Class hierarchy shown.Class A is the superclass from which is derived Class B. Class C and
Class D are further derived from Class B. Now if Class A contains a bug, the bug will also be present in the
Child Classes.But when we correct the bug in Class A, automatically the bug is corrected in ALL the child
classes as well.This transitive nature of inheritance reduces efforts required for maintenance.

Class A
Class B
Class C

Class D

extends keyword
The extends keyword is used implement inheritance in java.For example to derive Class B (sub class)
from Class A (super class) the syntax is : classB extends classA{ .}
Types of Inheritance
No Inheritan
What it is?
ce
1
Simple
One sub class inherits from only one base
Inheritan
class.
ce
Example : Class B is the sub class and it
inherits from base class Class A.
2

Multiple
Inheritan
ce*

Hierarchi
al
Inheritan
ce

One sub class inherits from many base


classes.
Example : Class C is the sub class and it
inherits from base classes Class A and Class
B.
Many sub classes inherit from one base class.
Example : Class B and Class C are the sub
classes which are derived from Class A.

Example

Class A
Class B
Class A

Class B
Class C
Class A

Class B

Hybrid
Inheritan
ce

The sub class inherits from more many base


classes, but the base classes further inherit
from a single base class.
Example : Class D is the sub class and it
inherits from base classes Class B and Class C
which are derived from Class A.

Class C

Class A
Class B

Class C
Class D

Multilevel
Inheritan
ce

The sub class inherits from a base class and


but the base classes further inherit from
another base class.
Example : Class C is the sub class and it
inherits from base class, Class B which is
derived from Class A.
*Java does not support Multiple Inheritance and Hybrid Inheritance

Class A
Class B
Class C

Access Specifiers or Visibility Modifiers (for Data Members and Methods)


Access specifiers control how data members and methods of a class are accessible outside it. Java access
specifiers are private, default (no access specifier), protected and public.
Visibility Increases

private
Data members and
methods
are
accessible only from
within its own class.

default (no specifier)


Data
members
and
methods are accessible
within its own class and
to other classes in the
same package.

protected
Data
members
and
methods are accessible
within its own class,to
other classes in the
same package and to
sub classes even if the
sub class is in a
different package.

public
Data
members
and
methods
are
accessible
everywhere the class is
accessible.

IMP: THE ABOVE MATTER SHOULD BE VERY VERY CLEARLY UNDERSTOOD


Hiding Data Members or Hiding Member Variables
When the sub class has data members with the same name as the super class, the super classs data
members are hidden by the child classs data members.The only way to access the super class variable
is using the keyword super.

//Base Class
class book
{
String bookName; //Hidden data member
}

//Derived Class or Child Class


class novel extends book
{
String bookName;
public novel(String bname1,String bname2)
{
bookName=bname1; //Superclass variable
hidden
super.bookName=bname2;
}
public void display()
{
System.out.println(bookName);
System.out.println(super.bookName);
}
}

package eg05b;
public class eg05b
{
public static void main(String args[])
{
novel n=new novel("Ravens of
Doom","Frankenstein");
n.display();
}
} O/P:
Ravens of Doom
Frankenstein

Method Overriding (Shadowing)


When the sub class has methods with the same name and parameter list as the super class, the super
classs methods are overridden or shadowed by the child classs methods.The only way to access the
super class method is using the keyword super.
//Base Class
class book
{
String bookName;
public void display()
//Overridden Method
{
System.out.println("Super Class");
}
}
package eg05c;
public class eg05c
{
public static void main(String args[])
{
novel n=new novel("Last of the Moas");
n.callDisplay();
}
} O/P:
Sub Class
Super Class

//Derived Class or Child Class


class novel extends book
{
public novel(String bname)
{
super.bookName=bname;
}
public void display()
{
System.out.println("Sub Class");
}
public void callDisplay()
{
display(); //Superclass method overridden
super.display();
}
}

super keyword
The super keyword is used to refer to the super class of the current class.It may be used to refer to a
super class data member or invoke a super class constructor or a super class method.
Invoking a super class method
super.methodname(<list of arguments>)
Invoking a super class constructor
a)The only way to invoke a superclass constructor from a sub class is
super() or super(<list of arguments>)
b)The call to the superclass constructor must be the first statement in the sub class constructor.
final keyword
1)The final keyword specifies that the value of a variable is permanent and cannot be changed later.
Eg final double PI=3.1416;

2)A final method may not be overridden by methods of the child class.
Eg public final void display() { }
3)A final class cannot be extended. ie it cannot have sub classes.
Eg public final class MyClass {...}
Method Overloading or Function Overloading
Method overloading refers to defining many methods in the same class which have the same name but
different number of arguments or different type of arguments.
package eg05d;
public class eg05d
{
public static void main(String args[])
{
String n="John";
MyClass mc=new MyClass();
mc.display();
mc.display(n);
}
}

No
1
2

class MyClass
{
public void display()
//Overloading
{
System.out.println("Hello there");
}
public void display(String name)
//Overloading
{
System.out.println("Hello there
"+name);
}
}

Method Overloading
Method Overloading takes place for methods
of the same class.
Overloading does not block inheritance from
super class.

Overloaded Methods must have the different


signatures.ie Same name but different
parameter lists/ type of arguments.

During method overloading, the return type is


not important.

Method Overriding
Method Overriding takes place for methods of a
super class and a sub class.
Overriding blocks inheritance from the super class.
ie the sub class method replaces the super class
method.
Overridden methods must have the same
signature. ie A super class method can be
overridden only by a child class method with same
name and same parameter list/type of arguments.
During method overriding, the return type of both
methods must be the same.

Need or Advantage of Method Overridding


Overridding methods allow Java to support
polymorphism ie ability of an object to behave
differently in different circumstances. It allows a
general super class to specify methods that will be
common to all of its sub classes, while allowing
subclasses to define specific implementations of the
methods.

Need or Advantage of Method Overloading


Overloading methods allow Java to support
polymorphism ie ability of an object to behave
differently in different circumstances. When we
want a method to implement similar functionality
for different data types, overloading is a better
option than creating many functions of similar
names. The value of overloading is that it allows
related methods to be accessed by use of a
common name.
Eg instead of creating abs() for finding absolute
value of integer, fabs() for absolute value of float,
dabs() for double etc Java has overload the abs()
method with different data types as argument.

Eg int abs(int), float abs(float), double abs(double)


DIFFERENT METHODS ARE CALLED DEPENDING
UPON DATA TYPE AND/OR NUMBER OF
ARGUMENTS.

DIFFERENT METHODS ARE CALLED DEPENDING


UPON WHETHER METHOD IS CALLED ON
SUPER CLASS OBJECT OR SUB CLASS OBJECT.
The Object class
The Object class is the super class of ALL classes in
Java.All classes created in Java are inherited, either
implicitly or explicitly from the Object Class.
Therefore reference variables of type Object can
refer to instances of all classes. Eg ->

Object o;
o="Holiday";
o=new
Scanner(System.in);
o=new A();

class A
{
String name;
}

Inheritance Graph or Java Class Hierarchy


The hierarchy of Java Classes which may be graphically depicted as a tree with the Object Class as the root
of the tree is known as the Inheritance Graph.
Method Overloading Vs Method Overriding
class book
package eg07;
{
public class eg07
String bookName;
{
String authorName;
public static void main(String args[])
double price;
{
book mybook=new book("Meat is
public book(String bName,String aName,double
Murder!",
p)
"Brottman",40);
{
mybook.display();
bookName=bName;
mybook.display(0);
authorName=aName;
novel n1=new novel("Dark Hollow",
price=p;
"Brian Keane", 50,"Horror",7);
}
n1.display();
}
public void display()
}
{
class novel extends book
System.out.println("Book
Name :"+bookName);
{
String category;
System.out.println("Author
Name :"+authorName);
int rating;
public novel(String bName,String aName,double
System.out.println("Price
:"+price);
}
p,
String cat,int rat)
public void display(int i)
{
{
Overloads
super(bName,aName,p);
if (i==0)
display() of the
System.out.println("The
Book
is
category=cat;
same class- book
rating=rat;
"+bookName);
else if (i==1)
}
public void display()
System.out.println("The Author is
Overrides
"+authorName);
{
display() of the
super.display();
else if(i==2)
super class- book
System.out.println("The Price is "+price);
System.out.println("Category :"+category);
System.out.println("Rating :"+rating);
}
}
}
}

//Note1: Notice that when overloading, the method signatures (number of arguments or type of parameter
is dffierent while when overriding the the signature is same..
Abstract Classes
An abstract class is a superclass that defines a general concept without providing the implementation of
abstract methods.ie the abstract super class will contain the definition of abstract methods but not the
method bodies.The sub classes have to implement the abstract method and provide the method body. The
abstract class is meant to be extended and we are not allowed to create instances of the abstract class.
An abstract class is created using the abstract keyword.
Interfaces
An interface is a classlike construct that defines a protocol of behavior without providing the
implementation of abstract methods.ie the interface will contain the definition of abstract methods but not
the method bodies.The classes which implement the interface have to implement the abstract method and
provide the method body. The interface is meant to be implemented and we are not allowed to create
instances of the interface. An interface is implemented using the implements keyword. An Interface can
only have static final constants and abstract methods.
Abstract Method
Abstract methods are methods defined in Abstract classes or Interfaces with the key word abstract. They
have no method body and sub classes are expected to provide the method body.
Abstract Class Example
Interface Example
package eg08;
package eg09;
public class eg08
public class eg09
{
{
public static void main(String args[])
public static void main(String args[])
{
{
sub s=new sub();
sub s=new sub();
s.display();
s.display();
}
}
}
}
abstract class disp
interface T1
{
{
public abstract void display();
public static final int k=10;
}
public abstract void display();
}

Abstract

Abstract

class sub extends disp


class sub implements T1
method
method
{
{
definition
definition
public void display()
public void display()
{
{
System.out.println("Hello");
System.out.println(k);
}
}
Abstract
Abstract
}
}
method
method
Note1 : A sub class of an abstract class must implement the abstract method(s) or it also must
be declared
implementati
implementati
as abstract.
Note2: We cannot create an instance of disp class,but we can create instance of sub class.
disp d=new disp();
T1 t=new T1();
No
1

Abstract Class
An abstract class may contain normal data
members and methods in addition to abstract
methods.
A child class may only extend one abstract
class as multiple inheritance is not allowed in
Java.
An abstract class may have a constructor

Interface
An Interface can only have static final constants and
abstract methods.
A class may implement more than one interface
thus creating the effect of multiple inheritance.
An interface cannot have a constructor.

which can be called by a sub class.


abstract keyword is used
eg
abstract class disp
{
public abstract void display();
}

implements keyword is used


eg
interface T1
{
public static final int k=1; //static, final not
mandatory*
public abstract void p();
}
*Since in an interface,data members must be public static and final and methods must be public and
abstract, java allows these modifiers to be omitted.
No
Multiple Inheritance (not allowed in
Interface
Java)
1
A base class may contain normal data
An Interface can only have static final constants and
members and methods in addition to abstract abstract methods.*
methods.
2
In multiple inheritance, there is always a
Unrelated classes can implement the same
hierarchy of classes.
Interface
In Java a Sub Class can also be a Super Class.Comment. or Super Class References and Sub
Class objects.
Java is a strongly typed language and type checking is strictly enforced.Therefore normally a variable
reference of one class cannot refer to an object of another of class.However, there is an important
exception A REFERENCE VARIABLE OF A SUPER CLASS CAN REFER TO AN OBJECT OF ITS SUB CLASS.
Not Allowed
Allowed
Class A and Class B are unrelated.
Class B is derived from Class A

Class A

Class B

Class A
Class B

A a=new B();
A a=new B();
You need to go through Practical questions from the text book for this chapter.And it will require time and
effort.

10

You might also like