Java Inheritance and Interfaces Guide
Java Inheritance and Interfaces Guide
UNIT II
Inheritance –Definition, single inheritance, benefits of inheritance, Member
access rules, super class,
polymorphism- method overriding, Dynamic method dispatch, using final with
inheritance, abstract classes,
Base class object.
It can override methods that are inherited from its parent class.
Inheritance Basics
The key word extends is used to define inheritance in Java.
Syntax:-
//base class:
class A{ A
//members of A
}
//Derived class syntax: B
class B extends A{
//members of B
}
// Java Program to illustrate Inheritance
import [Link].*;
// Driver Class
class Gfg {
public static void main(String args[])
{
Engineer E1 = new Engineer();
[Link]("Salary : " + [Link]+ "\nBenefits : “
+[Link]);
}
}
The Benefits of Inheritance
Software Reusability ( among projects )
Code ( class/package ) can be reused among the projects.
Ex., code to insert a new element into a table can be written once and
reused.
//Single Inheritance
class A{
}
class B extends A{
}
//Multilevel Inheritance
class A{
}
class B extends A{
}
class C extends B{
}
//Hierarchical Inheritance
class X{
}
class B extends X{
}
class C extends X{
}
//Multiple Inheritance
class A{
}
class B {
}
class C extends A , B
{
} //Wrong code
➢ Multiple Inheritance can be implemented by implementing multiple
interfaces not by extending multiple classes.
Example :
//Multiple Inheritance
class B extends A implements C , D
interface one{
{
}
} OK interface two{
}
class A implements one, two{
}
} } WRONG
Hybrid inheritance:-
▪Hybrid is combination of hierarchical & multiple inheritance .
▪Java is not supporting hybrid inheritance
because multiple inheritance(not supported by java)
is included in hybrid inheritance.
class A {
A() {
[Link] ("Inside A's constructor.");
} C
} B
class B extends A { A
B() {
[Link]("Inside B's constructor.");
}
}
class C extends B {
C() { oc
[Link]("Inside C's constructor.");
}
}
class CallingCons A Output:
{ public static void main(String args[])
{ Inside A’s constructor
C oc = new C(); Inside B’s constructor
oaa
Inside C’s constructor
}
}
Super Keyword
Subclass refers to its immediate super class by using super keyword.
• super has two general forms.
• First it calls the super class constructor.
• Second is used to access a member of the super class that has been
hidden by a member of a subclass.
Super keyword:-
Super keyword is holding super class object. And it is representing
▪Super class variables
▪Super class methods
Super class constructors
Using super to call super class constructors
super (parameter-list);
• parameter-list specifies any parameters needed by the constructor in the
super class.
• super( ) must always be the first statement executed inside a subclass
constructor.
Super keyword required:-
class Parent
[Link](super.a+super.
{
b); //super class variables
int a=10,b=20; //instance variables
addition
};
class Child extends Parent
{ //instance variables
int a=100; public static void main(String[] args)
int b=200; { Child c = new Child();
void m1(int a,int b) c.m1(1000,2000);
//local variables }
{ };
[Link](a+b); //In above example sub class and
//local variables addition super class having same variable
[Link](this.a+this.b); names hence to represent.
//current class variables addition //a)sub class variables use this
} keyword.
//b)Super class variables use super
keyword.
super class and sub class contains methods with same names
class Parent
{ Ex.Program2:
void m1(int a)
{ class Parent
[Link]("parent m1()-->"+a); } { void m1() {
}; [Link]("parent m1() method");}
class Child extends Parent };
{
void m1(int a) class Child extends Parent
{ {
[Link]("child m1()-->"+a); void m1()
} {
void m2() [Link]("child class m1() method");}
{ void m3()
this.m1(10);//child class m1(int) method { this.m1();//current class method is executed
calling super.m1();//super class method will be
[Link]("child m2()"); executed
super.m1(100);// parent class m1(int) }
method calling public static void main(String[] args)
} { new Child().m3();
public static void main(String[] args) }
{ Child c = new Child(); c.m2(); };
}
// Using super to overcome name hiding.
class A {
int i;
}
class B extends A // Create a subclass by
extending class A.
{ int i; // this i hides the i in
A
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}
void show() {
[Link]("i in superclass: " + super.i);
[Link]("i in subclass: " + i);
}
}
class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
[Link](); This program displays the following:
} i in superclass: 1
} i in subclass: 2
Example:- To call super class constructor use super keyword.
➢ Polymorphism is a Greek word poly means many and morphism means forms.
There are two types of polymorphism in java
class Smethod
{
static void display()
{
[Link]( "HI from display");
}
}
class Statictest
{
public static void main(String a[])
{
[Link]();
}
}
class Smethod
{
static int x=10;
static void display()
{
[Link]( "HI from display");
[Link]( x );
}
}
class statictest
{
public static void main(String a[])
{
[Link]();
}
}
class Smethod
{
int x=10;
static void display()
{
[Link]( "HI from display");
[Link]( x );
}
}
class statictest
{
public static void main(String a[])
{
[Link]();
}
}
Static Blocks:
class statictest
class Sblock
{
{
public static void main(String a[])
static
{
{
[Link]("Hi from static block" ); Sblock s = new Sblock();
}
}
}
Sblock()
{
[Link]("Hi from constructor" );
}
class FinalDemo{
public static void main(String sree[]){
final int i=20;
System [Link](i);
//i=i+1; can’t assign a value to final variable i
//[Link](i); cannot assign a value to final variable i
}
}
To prevent overriding
To disallow a method from being overridden, specify final as a modifier at
the start of its declaration. Methods declared as final cannot be overridden.
class A {
final void display() {
[Link]("This is a final method.");
}
}
class B extends A {
void display() { // ERROR! Can't override.
[Link]("Illegal!");
}
}
To prevent inheritance
→To prevent a class from being inherited precede the class declaration with
final.
→Declaring a class as final implicitly declares all of its methods as final, too.
→It is illegal to declare a class as both abstract and final since an abstract class
is incomplete by itself and relies upon its subclasses to provide complete
implementations.
final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
}
➢ Normally, Java resolves calls to methods dynamically, at run time. This
is called late binding.
➢ However, since final methods cannot be overridden, a call to one can
be resolved at compile time. This is called early binding.
Abstract Classes
➢ Data abstraction is the process of hiding certain details and showing only
essential information to the user.
Abstraction can be achieved with abstract classes
Abstract class: is a restricted class that cannot be used to create objects (to
access it, it must be inherited from another class).
➢ Any class that contains one or more abstract methods must also be declared
abstract.
Abstract method: A method that has been declared but not defined is an
abstract method.
Abstract method can only be used in an abstract class, and it does not have a
body. The body is provided by the subclass (inherited from)
➢ You must declare the abstract method with the keyword abstract:
abstract type name (parameter-list);
➢ You cannot instantiate (create a new instance of) an abstract class but you
can create reference to an abstract class.
➢ You can declare a class to be abstract even if it does not contain any
abstract methods. This prevents the class from being instantiated.
➢ This means that a reference variable of type Object can refer to an object
of any other class.
boolean equals(Object object) ………….. Determines whether one object is equal to another.
void notifyAll( ) ………… Resumes execution of all threads waiting onthe invoking object.
➢Using the keyword interface, you can fully abstract a class’ interface
from its implementation.
Once an interface has been defined, one or more classes can implement that
interface.
The general form of a class that includes the implements clause looks like this:
Import [Link].*;
interface printable{
Public Abstract void print();
}
class A6 implements printable{
public void print(){[Link]("Hello");}
➢ If a class implements two interfaces that declare the same method, then the
same method will be used by clients of either interface.
➢ Also, the type signature of the implementing method must match exactly
the type signature specified in the interface definition.
interface SoundType{
void sound();
}
class Person implements SoundType class Cat implements SoundType class Radio implements SoundType
{ { {
public void sound() public void sound() public void sound()
{ { {
[Link]("Hello I am [Link]( [Link]( "I can sing a
human being"); "Meeeeeowwwwwwww"); song for you");
} } }
void display() } }
{ public class InterfaceEx
[Link](“Hi”);
{ public static void main(String[] args)
}
} { Person p=new Person();
Cat c=new Cat();
Radio r=new Radio();
SoundType s;
s=p;
[Link]();
[Link](); // Error
s=c;
[Link]();
s=r;
[Link]();
} }
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.
Output: i = 100
FinalTest :Show()
FinalDemo Varaible i :100
Interfaces Can Be Extended
One interface can inherit another by use of the keyword extends.
CLASS INTERFACE
➢The ‘class’ keyword is used to create a ➢The ‘interface’ keyword is used to create
class. an interface
➢An object of a class can be created. ➢An object of an interface cannot be
created.
➢Class doesn’t support multiple ➢Interface supports multiple inheritance.
inheritance.
➢A class can inherit another class. ➢An Interface cannot inherit a class.
➢A class can be inherited by another class ➢An Interface can be inherited by a class
using the keyword ‘extends’. using the keyword ‘implements’ and it can
be inherited by another interface using the
keyword ‘extends’.
➢A class can contain constructors. ➢An Interface cannot contain constructors.
➢It cannot contain abstract methods. ➢It consists of abstract methods only.
➢Variables and methods can be declared ➢Variables and methods are declared as
using any specifiers like public, protected, public only.
default, private.
Abstract Class Vs Interface
➢ An abstract class is written when there are some common features are shared
among the objects.
➢ An interface is written when all the features are implement differently in
different objects.
➢ An abstract class contains some abstract methods and also some concrete
methods.
➢ An interface contains only abstract methods.
➢ An abstract class can only inherit a single super class (abstract or otherwise).
➢ A class can implement more than one interface.
➢ Interfaces have no direct inherited relationship with any particular class, they are
defined independently. Interfaces themselves have inheritance relationship
among themselves.