Unit 2 Inheritance in JAVA
Unit 2 Inheritance in JAVA
• Inheritance –Definition,
• Single Inheritance,
• benefits of inheritance,
• Member access rules,
• super classes,
• polymorphism- method overriding,
• using final with inheritance,
• abstract classes,
• Base class object.
• Defining an interface
• Implementing an interface
• Differences between classes and interfaces
• Implements and extends keywords
• An application using an interfaces and uses of interfaces
Inheritance
-The mechanism of deriving a new class from an
existing class is known as inheritance.
-Existing class is known as base class or parent class
or super class and
-new class is known as derived class or child class or
sub class.
-In inheritance base class members are inherited to
derived class and also new members can be added to
derived class.
• By Inheritance, we are constructing new abstraction from the existing
one with extending or specializing the parents methods, and adding
new methods or properties.
• When a child class(newly defined abstraction) inherits(extends) its
parent class (being inherited abstraction), all the properties and
methods of parent class becomes the member of child class. In
addition, child class can add new data fields(properties) and
behaviors(methods), and can override methods that are inherited from
its parent class.
Types of Inheritance
1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
Contd..
Single Inheritance Hierarchical Inheritance
A A X X
B B A B C A B C
B B
C C
C C
Syntax of Derived class:
class subclass-name extends superclass-name {
// body of class
}
Single Inheritance
-Derivation of a class from only one base class is called
single inheritance.
A base class:
class A
{
B
//members of A
}
Derived class syntax:
class B extends A
{
//members of B
}
// A simple example of inheritance.
// Create a superclass.
class A {
int i, j;
/* The subclass has access to all public members of
void showij() {
System.out.println("i and j: " + i + " " + j); its superclass. */
} subOb.i = 7;
} subOb.j = 8;
// Create a subclass by extending class A. subOb.k = 9;
class B extends A { System.out.println("Contents of subOb: ");
int k; subOb.showij();
void showk() { subOb.showk();
System.out.println("k: " + k);
}
System.out.println();
void sum() { System.out.println("Sum of i, j and k in subOb:");
System.out.println("i+j+k: " + (i+j+k)); subOb.sum();
} }
} }
class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
The Benefits of Inheritance
• Message-Passing Overhead
– Message passing is more costly than invoking procedures.
• Program Complexity
– Overuse of inheritance often increases program complexity.
Member access rules
A subclass includes all of the members of its superclass
except private members.
Remember
A class member that has been declared as private will
remain private to its class. It is not accessible by any
code outside its class, including subclasses.
// Create a superclass.
class A {
int i; // public by default
private int j; // private to A
void setij(int x, int y) {
i = x;
j = y;
}
}
// A's j is not accessible here.
class B extends A {
int total;
void sum() {
void sum() {
super(parameter-list);
general form:
super.member
class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override.
}
}
Using final to Prevent Inheritance
classes declared as final cannot be inherited.
Declaring a class as final implicitly declares all of its methods as
final.
It is illegal to declare a class as both abstract and final, because
an abstract class is incomplete by itself and depends upon its
subclasses to provide complete implementations.
final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
}
Abstract Classes
A method that has been declared but not defined is an abstract method.
You must declare the abstract method with the keyword abstract:
abstract type name(parameter-list);
You can declare a class to be abstract even if it does not contain any
abstract methods
This prevents the class from being instantiated.
Ex:-
abstract class A {
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo() {
System.out.println("This is a concrete method.");
}
}
class B extends A {
void callme() {
System.out.println("B's implementation of callme.");
}
}
class AbstractDemo {
public static void main(String args[]) {
B b = new B();
b.callme();
b.callmetoo();
}
}
Base Class Object
• In java, all classes use inheritance.
• If no parent class is specified explicitly, the base class Object is implicitly inherited.
• All classes defined in Java, is a child of Object class, which provides minimal
functionality guaranteed to be common to all objects.
Method Purpose
Object clone( ) Creates a new object that is the same as the 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
invoking object.
void notify( ) Resumes 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( ) Waits on another thread of execution.
void wait(long milliseconds)
void wait(long milliseconds,int nanoseconds).
Interfaces
• Interfaces are syntactically similar to classes, but they
lack instance variables, and their methods are declared
without any body.
• Any number of classes can implement an interface.
• One class can implement any number of interfaces.
Defining an Interface
• The general form of an interface:
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
Example:
interface Callback {
void callback(int param);
}
Contd..
• Here, access is either public or not used.
– Default indicates, the interface is only available to other
members of the package in which it is declared.
– Public indicates, the interface can be used by any other
code.
void nonIfaceMeth() {
System.out.println(“Non Interface Method….");
}
}
Accessing Implementations Through Interface
References
• Any instance of any class that implements the interface can be referred by
an interface variable.
• When you call a method through an interface variable, the correct
version will be called based on the actual instance of the class referred by
the variable.
• This is one of the key features of interfaces.
interface Callback {
void callback(int
param);
}
Output:
callback called with 42
Partial Implementations
If a class includes an interface but does not fully implement the methods defined
by that interface, then that class must be declared as abstract.
abstract class Incomplete implements Callback{
int a, b;
void show() {
System.out.println(a + " " + b);
}
// ...
}
If a class includes an interface but does not fully implement the methods defined
by that interface, then that class must be declared as abstract.
Here, the class Incomplete does not implement callback( ) and must be
declared as abstract.
Any class that inherits Incomplete must implement callback( ) or be declared
abstract itself.
Variables in Interfaces
You can define variables in an interface but implicitly they are final variables.
That is you can’t modify them .
FinalTest.java
class FinalImpl implements FinalDemo{
public void show(){
System.out.println("FinalTest :Show()");
}
FinalDemo.java }
interface FinalDemo{ class FinalTest{
int i=100; public static void main(String sree[]){
void show(); FinalImpl fi=new FinalImpl();
} fi.show();
//fi.i=200; can’t assign a value to variable i
System.out.println("FinalDemo Varaible i :"+fi.i);
}
} Output:
FinalTest :Show()
FinalDemo Varaible i :100
Interfaces Can Be Extended
One interface can inherit another by use of the keyword extends.
Interfaces have no direct inherited relationship with any particular class, they
are defined independently.
A class can implement more than one interface. By contrast, a class can only
inherit a single superclass (abstract or otherwise).
Abstract Class Vs Interface
An abstract class is written when there are some common features shared by all the objects.
An interface is written when all the features are implement differently in different objects.
When an object class is written, it is the duty of the programmer to provide sub classes to it.
An interface is written when the programmer wants to leave the implementation to the third party
vendors.
An abstract class contains some abstract methods and also some concrete methods.
An interface contains only abstract methods.
An abstract class can contain instance variables also.
An interface can not contain instance variables. It contains only constants.
All the abstract methods of the abstract class should be implemented in its sub classes.
All the (abstract) methods of the interface should be implemented in its implementation classes.
Abstract class is declared by using the keyword abstract.
Interface is declared using the keyword interface.
A class can implement more than one interface.
An abstract class can only inherit a single super class (abstract or otherwise).
Interfaces have no direct inherited relationship with any particular class, they are defined
independently. Interfaces themselves have inheritance relationship among themselves.
• Define an interface “GeometricShape” with methods area ()
and perimeter () (Both methods return type and parameter list
should be void and empty respectively).
• Define classes like Triangle, Rectangle and Circle
implementing the “GeometricShape” Interface and also define
“ExecuteMain” class in which includes main method to test
the above class
Uses of Interface
To reveal an object's programming interface (functionality of the object)
without revealing its implementation.
– This is the concept of encapsulation.
– The implementation can change without affecting the caller of the
interface.