UNIT3

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

UNIT-III:

INHERITANCE: Inheritance Basics, Types of Inheritance, The Keyword ‘super’, Final with
inheritance.
POLYMORPHISM: Method Overriding, Dynamic Method Dispatch, Abstract Classes.
INTERFACES: Interface, Multiple Inheritance using Interface, Abstract Classes vs. Interfaces.

INHERITANCE

The process of obtaining the data members and methods from one class to another class is
known as inheritance. It is one of the fundamental features of object-oriented programming.

Important points

 In the inheritance the class which gives data members and methods is known as base
or super or parent class.
 The class which is taking the data members and methods is known as sub or derived
or child class.
 The concept of inheritance is also known as re-usability or extendable classes or sub
classing or derivation.

Why use Inheritance ?

 For Method Overriding (used for Runtime Polymorphism).


 It's main uses are to enable polymorphism and to be able to reuse code for different
classes by putting it in a common super class
 For code Re-usability

Syntax of Inheritance

class Subclass-Name extends Superclass-Name


{
//methods and fields
}

Advantage of inheritance
If we develop any application using concept of Inheritance than that application have
following advantages,
 Application development time is less.
 Application takes less memory.
 Application execution time is less.
 Application performance is enhance (improved).
 Redundancy (repetition) of the code is reduced or minimized so that we get
consistence results and less storage cost.

Types of Inheritance
Based on number of ways inheriting the feature of base class into derived class we have five
types of inheritance; they are:

 Single inheritance

 Multiple inheritance

 Hierarchical inheritance

 Multilevel inheritance

 Hybrid inheritance

SINGLE INHERITANCE

In single inheritance there exists single base class and single derived class.
EXAMPLE:

class Employee
{
float salary=60000;
}
class Science extends Employee
{
float bonous=2000;
public static void main(String args[])
{
Science obj=new Science();
System.out.println("Salary is:"+obj.salary);
System.out.println("Bonous is:"+obj.bonous);
}
}

OUTPUT:

Salary is: 60000.0


Bonous is: 2000.0

MULTILEVEL INHERITANCES

In Multilevel inheritances there exists single base class, single derived class and multiple
intermediate base classes.
EXAMPLE:

class Employee
{
float total_sal=0, salary=50000;
}

class HRA extends Employee


{
float hra=3000;
}

class DA extends HRA


{
float da=2000;
}

class Science extends DA


{
float bonous=2000;
public static void main(String args[])
{
Science obj=new Science();
obj.total_sal=obj.salary+obj.hra+obj.da+obj.bonous;
System.out.println("Total Salary is:"+obj.total_sal);
}
}

OUTPUT:

Total Salary is: 57000.0

MULTIPLE INHERITANCE
In multiple inheritance there exist multiple classes and single derived class.
The concept of multiple inheritance is not supported in java through concept of classes but it can
be supported through the concept of interface.

HYBRID INHERITANCE

Combination of any inheritance type

In the combination if one of the combination is multiple inheritance then the inherited
combination is not supported by java through the classes concept but it can be supported through
the concept of interface.

MEMBER ACCESS AND INHERITANCE


Although a subclass includes all of the members of its superclass, it cannot access those
members of the superclass that have been declared as private

EXAMPLE:

/* In a class hierarchy, private members remain


private to their class.

This program contains an error and will not


compile. */
// 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() {
total = i + j; // ERROR, j is not accessible here
}
}
class Access {
public static void main(String args[]) {
B subOb = new B();
subOb.setij(10, 12);
subOb.sum();
System.out.println("Total is " + subOb.total);
}
}

SUPER KEYWORD
 The super keyword in java is a reference variable that is used to refer immediate parent
class object.

 Whenever you create the instance of subclass, an instance of parent class is created
implicitly i.e. referred by super reference variable.

Usage of java super Keyword

 super is used to refer immediate parent class instance variable.

EXAMPLE:

class Employee
{
float salary=10000;
}
class HR extends Employee
{
float salary=20000;
void display()
{
System.out.println("Salary: "+super.salary);//print base class salary
}
}
class Supervarible
{
public static void main(String[] args)
{
HR obj=new HR();
obj.display();
}
}

OUTPUT:

Salary: 10000.0

 super() is used to invoke immediate parent class constructor.

EXAMPLE:

class Employee
{
Employee()
{
System.out.println("Employee class Constructor");
}
}
class HR extends Employee
{
HR()
{
super(); //will invoke or call parent class constructor
System.out.println("HR class Constructor");
}
}
class Supercons
{
public static void main(String[] args)
{
HR obj=new HR();
}
}
OUTPUT:

Employee class Constructor


HR class Constructor

 super is used to invoke immediate parent class method.

EXAMPLE:

class Student
{
void message()
{
System.out.println("Good Morning Sir");
}
}

class Faculty extends Student


{
void message()
{
System.out.println("Good Morning Students");
}

void display()
{
message(); //will invoke or call current class message() method
super.message(); //will invoke or call parent class message() method
}

public static void main(String args[])


{
Student s=new Student();
s.display();
}
}

OUTPUT:

Good Morning Students


Good Morning Sir
WHEN CONSTRUCTORS ARE CALLED

When a class hierarchy is created, in what order are the constructors for the classes that make up
the hierarchy called? For example, given a subclass called B and a superclass called A, is A’s
constructor called before B’s, or vice versa? The answer is that in a class hierarchy, constructors
are called in order of derivation, from superclass to subclass. Further, since super( ) must be the
first statement executed in a subclass’ constructor, this order is the same whether or not super( )
is used. If super( ) is not used, then the default or parameterless constructor of each superclass
will be executed

EXAMPLE:

// Create a super class.


class A {
A() {
System.out.println("Inside A's constructor.");
}
}

// Create a subclass by extending class A.


class B extends A {
B() {
System.out.println("Inside B's constructor.");
}
}

// Create another subclass by extending B.


class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}
class CallingCons {
public static void main(String args[]) {
C c = new C();
}
}

OUTPUT :
Inside A’s constructor
Inside B’s constructor
Inside C’s constructor
METHOD OVERRIDING

 In a class hierarchy, when a method in a subclass has the same name and type signature
as a method in its superclass, then the method in the subclass is said to override the
method in the superclass.

 When an overridden method is called from within a subclass, it will always refer to the
version of that method defined by the subclass.

 The version of the method defined by the superclass will be hidden.

// Method overriding.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}

// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}

// display k – this overrides show() in A


void show() {
System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}

OUTPUT

k: 3
Rules for Method Overriding in Java

 The access level can't be more restrictive than the overridden method's
 Private Methods cannot be Overridden

 Final Methods cannot be overridden in Java

 Static Methods cannot be overridden

 Overriding Method must have the same return type (or Covariant return type)
 You cannot override constructor as the constructor name of the base class and child class
can never be same

ABSTRACT CLASSES

 A class that is declared with abstract keyword is known as abstract class in java.

 It can have abstract and non-abstract methods

 To declare a class abstract, you simply use the abstract keyword in front of the
class keyword at the beginning of the class declaration.

 There can be no objects of an abstract class. That is, an abstract class cannot be directly
instantiated with the new operator.

 Such objects would be useless, because an abstract class is not fully defined.

 Any sub-class extending from an abstract class should either implement all the abstract
methods of the super-class or the sub-class itself should be marked as abstract

 It is not necessary to add the abstract methods only in the super most class, we can add
more abstract methods in the sub-classes.

EXAMPLE:

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();
}
}
OUTPUT:

B's implementation of callme


This is a concrete method

USING FINAL TO PREVENT OVERRIDING

 While method overriding is one of Java’s most powerful features, there will be times
when you will want to prevent it from occurring.

 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.

EXAMPLE:

class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}
USING FINAL TO PREVENT INHERITANCE

 Sometimes you will want to prevent a class from being inherited.


 To do this, precede the class declaration with final.
 Declaring a class as final implicitly declares all of its methods as final, too

EXAMPLE:

final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
}

DYNAMIC METHOD DISPATCH

 Dynamic method dispatch is the mechanism by which a call to an overridden method is


resolved at run time, rather than compile time.

 Dynamic method dispatch is important because this is how Java implements run-time
polymorphism

 When different types of objects are referred to, different versions of an overridden
method will be called.

 In other words, it is the type of the object being referred to (not the type of the reference
variable) that determines which version of an overridden method will be executed.

EXAMPLE:

class A {
void callme() {
System.out.println("Inside A's callme method");
}
}
class B extends A {
// override callme()
void callme() {
System.out.println("Inside B's callme method");
}
}
class C extends A {

// override callme()
void callme() {
System.out.println("Inside C's callme method");
}
}
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B

C c = new C(); // object of type C

A r; // obtain a reference of type A

r = a; // r refers to an A object

r.callme(); // calls A's version of callme

r = b; // r refers to a B object

r.callme(); // calls B's version of callme


r = c; // r refers to a C object

r.callme(); // calls C's version of callme


}
}

OUTPUT:

Inside A’s callme method


Inside B’s callme method
Inside C’s callme method
INTERFACE

Definition: Any service requirement specification (SRS) is considered as an interface


or
Pure abstract class is called interface

Interface is similar to class which is collection of public static final variables (constants) and
abstract methods.
The interface is a mechanism to achieve fully abstraction in java. There can be only abstract
methods in the interface. It is used to achieve fully abstraction and multiple inheritance in
Java.

Why we use Interface ?

 It is used to achieve fully abstraction.


 By using Interface, you can achieve multiple inheritance in java.
 It can be used to achieve loose coupling.

properties of Interface

 It is implicitly abstract. So we no need to use the abstract keyword when declaring an


interface.
 Each method in an interface is also implicitly abstract, so the abstract keyword is not
needed.
 Methods in an interface are implicitly public.
 All the data members of interface are implicitly public static final.

DEFINING AN INTERFACE

An interface is defined much like a class. This is 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);
}

IMPLEMENTING INTERFACES

access class classname [extends superclass]


[implements interface [,interface...]] {

// class-body

}
EXAMPLE :
interface Animal {

public void eat();


public void travel();
}

public class MammalInt implements Animal{

public void eat(){


System.out.println("Mammal eats");
}

public void travel(){


System.out.println("Mammal travels");
}

public int noOfLegs(){


return 0;
}
}
class Demo
{
public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();

}
}

OUTPUT:

ammal eats
ammal travels

INTERFACES CAN BE EXTENDED

One interface can inherit another by use of the keyword extends. The syntax is the
same as for inheriting classes. When a class implements an interface that inherits
another interface, it must provide implementations for all methods defined within
the interface inheritance chain

EXAMPLE:

// One interface can extend another.


interface A {
void meth1();
void meth2();
}

// B now includes meth1() and meth2() -- it adds meth3().


interface B extends A {
void meth3();
}

// This class must implement all of A and B


class MyClass implements B {
public void meth1() {
System.out.println("Implement meth1().");
}
public void meth2() {
System.out.println("Implement meth2().");
}
public void meth3() {
System.out.println("Implement meth3().");
}
}
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}

OUTPUT:

Implement meth1().
Implement meth2().
Implement meth3()

MULTIPLE INHERITANCE USING INTERFACE

interface AnimalEat {
void eat();
}
interface AnimalTravel {
void travel();
}
class Animal implements AnimalEat, AnimalTravel {
public void eat() {
System.out.println("Animal is eating");
}
public void travel() {
System.out.println("Animal is travelling");
}
}
public class Demo {
public static void main(String args[]) {
Animal a = new Animal();
a.eat();
a.travel();
}
}

OUTPUT:

Animal is eating
Animal is travelling
DIFFERENCE BETWEEN CLASS AND INTERFACE

Property Class Interface


Instantiation Can Be Instantiated Cannot be instantiated
State Each Object created will have its own Each objected created after
state implementing will have the same state
Behavior Every Object will have to define its
Every Object will have the same behavior
own behavior by implementing the
unless overridden.
contract defined.
Inheritance A Class can inherit only one Class and can An Interface cannot inherit any classes
implement many interfaces while it can extend many interfaces
Variables All the variables are static final by
All the variables are instance by default
default, and a value needs to be
unless otherwise specified
assigned at the time of definition
Methods All the methods should be having a
All the methods are abstract by default
definition unless decorated with an
and they will not have a definition.
abstract keyword

DIFFERENCE BETWEEN ABSTRACT CLASS AND INTERFACE

Abstract class Interface


1) Abstract class can have abstract and Interface can have only abstract methods.
non-abstractmethods.
2) Abstract class doesn't support multiple Interface supports multiple inheritance.
inheritance.
3) Abstract class can have final, non- Interface has only static and final variables.
final, static and non-static variables.
4) Abstract class can have static methods, Interface can't have static methods, main
main method and constructor. method or constructor.
5) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
6) The abstract keyword is used to The interface keyword is used to declare
declare abstract class. interface.
7) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

You might also like