0% found this document useful (0 votes)
35 views30 pages

Module 2 - MULTIPLE INHERITANCE - LectureNotes

The document discusses object oriented programming using Java. It covers various inheritance concepts including single inheritance, hierarchical inheritance, multilevel inheritance, and multiple inheritance through interfaces. Java supports single inheritance by extending a single superclass, but allows multiple inheritance through interfaces by implementing multiple interfaces. The document provides examples to illustrate each inheritance concept.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views30 pages

Module 2 - MULTIPLE INHERITANCE - LectureNotes

The document discusses object oriented programming using Java. It covers various inheritance concepts including single inheritance, hierarchical inheritance, multilevel inheritance, and multiple inheritance through interfaces. Java supports single inheritance by extending a single superclass, but allows multiple inheritance through interfaces by implementing multiple interfaces. The document provides examples to illustrate each inheritance concept.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Object Oriented Programming using Java

Module 2: Multiple Inheritance

Inheritance – Inheritance hierarchies- super and subclasses- member access rules- super
keyword- preventing inheritance: final classes and methods- the object class and its methods
Polymorphism –dynamic binding- method overriding- abstract classes and methods

Hierarchical abstractions & Concept of Inheritance:

o In OOP another important feature is Reusability which is very use full in two major
issues of development :
Saving Time
Saving Memory
o In C++/Java the mechanism implements this reusability is Inheritance.
o Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).
o The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.
o Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

General form of a class declaration is:


Class subclass-name extends super class-name
{
// body of super class
}

// A simple example of inheritance.

class Animal{
void eat(){
System.out.println("Eating...");
}
}
class Dog extends Animal{
void bark(){
System.out.println("Barking...");
}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();

Acharya Institute of Technology II sem


Object Oriented Programming using Java

}}

Output
Barking….
Eating…..

Forms of Inheretence:

1. Single Inheretence
2. Hierarichal Inherintence
3. Multiple Inherintence
4. Multilevel Inherintence
5. Hybrid Inherintence

Single Inherintence:

Derivation a subclass from only one super class is called Single Inherintence. In single inheritance, a

sub-class is derived from only one super class. It inherits the properties and behavior of a single-parent

class. Sometimes it is also known as simple inheritance.

General form of a class declaration is:


Class subclass-name extends super class-name
{
// body of super class
}
Example: Above inheritance example.

Hierarchical Inheritance:

Derivation of several classes from a single super class is called Hierarchical Inheritance.

Acharya Institute of Technology II sem


Object Oriented Programming using Java

Example:
class Student
{
public void methodStudent()
{
System.out.println("The method of the class Student invoked.");
}
}
class Science extends Student
{
public void methodScience()
{
System.out.println("The method of the class Science invoked.");
}
}
class Commerce extends Student
{
public void methodCommerce()
{
System.out.println("The method of the class Commerce invoked.");
}
}
class Arts extends Student
{
public void methodArts()
{
System.out.println("The method of the class Arts invoked.");
}
}
public class HierarchicalInheritanceExample
{
public static void main(String args[])
{
Science sci = new Science();
Commerce comm = new Commerce();
Arts art = new Arts();
//all the sub classes can access the method of super class
sci.methodStudent();

Acharya Institute of Technology II sem


Object Oriented Programming using Java

comm.methodStudent();
art.methodStudent();
}
}
Output:
The method of the class Student invoked.
The method of the class Student invoked.
The method of the class Student invoked.

Multilevel Inheritance:
In multi-level inheritance, a class is derived from a class which is also derived from
another class is called multi-level inheritance. In simple words, we can say that a class that has
more than one parent class is called multi-level inheritance. Note that the classes must be at different
levels. Hence, there exists a single base class and single derived class but multiple intermediate
base classes.

Example:
class Student
{
int reg_no;
void getNo(int no)
{
reg_no=no;
}
void putNo()
{
System.out.println("registration number= "+reg_no);
}
}
//intermediate sub class
class Marks extends Student
{
float marks;
void getMarks(float m)

Acharya Institute of Technology II sem


Object Oriented Programming using Java

{
marks=m;
}
void putMarks()
{
System.out.println("marks= "+marks);
}
}
//derived class
class Sports extends Marks
{
float score;
void getScore(float scr)
{
score=scr;
}
void putScore()
{
System.out.println("score= "+score);
}
}
public class MultilevelInheritanceExample
{
public static void main(String args[])
{
Sports ob=new Sports();
ob.getNo(0987);
ob.putNo();
ob.getMarks(78);
ob.putMarks();
ob.getScore(68.7);
ob.putScore();
}
}

Output:
registration number= 0987
marks= 78.0
score= 68.7

Multiple Inheritance (Through Interface):


Derivation of one class from two or more super classes is called Multiple Inheritance.

Acharya Institute of Technology II sem


Object Oriented Programming using Java

But java does not support Multiple Inheritance directly. It can be implemented by using interface
concept. An interface is an abstract "class" that is used to group related methods with "empty"
bodies: To access the interface methods, the interface must be "implemented" (kinda like
inherited) by another class with the implements keyword (instead of extends).
Consider following example:

Example:
class A
{
public void execute()
{
System.out.println("Hi.. Executing From Class A");
}
}
class B
{
public void execute()
{
System.out.println("Hi.. Executing From Class B");
}
}
class C extends A, B
{

}
public class Main
{
public static void main(String[] args)
{
C obj = new C(); // creating object of class C
obj.execute(); // execute() method is present in both class A and B
}
}
The above code gives error because the compiler cannot decide which execute() method is to
be invoked. Due to this reason, Java does not support multiple inheritances at the class level but
can be achieved through an interface.

Acharya Institute of Technology II sem


Object Oriented Programming using Java

Example:
// Java program to illustrate the
// concept of Multiple inheritance using interface
interface A
{
public void execute();
}
interface B
{
public void execute();
}
class C implements A, B
{
public void execute()
{
System.out.println("Hello.. From Implementation Class!!");
}
}
public class Main
{
public static void main(String[] args)
{
C obj = new C();
obj.execute();
}
}

Example 2:
interface Backend {

// abstract class
public void connectServer();
}

class Frontend {

public void responsive(String str) {


System.out.println(str + " can also be used as frontend.");
}
}

// Language extends Frontend class


// Language implements Backend interface
class Language extends Frontend implements Backend {

String language = "Java";

// implement method of interface

Acharya Institute of Technology II sem


Object Oriented Programming using Java

public void connectServer() {


System.out.println(language + " can be used as backend language.");
}

public static void main(String[] args) {

// create object of Language class


Language java = new Language();

java.connectServer();

// call the inherited method of Frontend class


java.responsive(java.language);
}

}
Output: Java can be used as backend language.
Java can also be used as frontend.

Hybrid Inheritance:

Derivation of a class involving more than one from on Inheritance is called Hydrid Inheritance
In general, the meaning of hybrid (mixture) is made of more than one thing. In Java, the hybrid
inheritance is the composition of two or more types of inheritance. The main purpose of using
hybrid inheritance is to modularize the code into well-defined classes. It also provides the code
reusability. The hybrid inheritance can be achieved by using the following combinations:
o Single and Multiple Inheritance (not supported but can be achieved through interface)
o Multilevel and Hierarchical Inheritance
o Hierarchical and Single Inheritance
o Multiple and Multilevel Inheritance

Example:
class HumanBody
{
public void displayHuman()
{
System.out.println("Method defined inside HumanBody class");

Acharya Institute of Technology II sem


Object Oriented Programming using Java

}
}
interface Male
{
public void show();
}
interface Female
{
public void show();
}
public class Child extends HumanBody implements Male, Female
{
public void show()
{
System.out.println("Implementation of show() method defined in interfaces Male and Female");
}
public void displayChild()
{
System.out.println("Method defined inside Child class");
}
public static void main(String args[])
{
Child obj = new Child();
System.out.println("Implementation of Hybrid Inheritance in Java");
obj.show();
obj.displayChild();
}
}

Defining a Subclass:

A subclass is defined as

Systax: class subclass-name extends superclass-name

Variable declaration;
Method declaration;

Acharya Institute of Technology II sem


Object Oriented Programming using Java

The keyword extends signifies that the properties of the super class name are extended to the
subclass name. The subclass will now contain its own variables and methods as well as those
of the super class. But it is not vice-versa.

Member access rules:


In Java, Access modifiers help to restrict the scope of a class, constructor, variable,
method, or data member. It provides security, accessibility, etc. to the user depending upon
the access modifier used with the element.

o Even though a subclass includes all of the members of its super class, it cannot
accessthose members who are declared as Private in super class. ―Super clas s Reference, Sub clas s Object‖.

1. Default Access Modifier


When no access modifier is specified for a class, method, or data member – It is said
to be having the default access modifier by default. The data members, classes, or methods
that are not declared using any access modifiers i.e. having default access modifiers are
accessible only within the same package.

2. Private Access Modifier


The private access modifier is specified using the keyword private. The methods or
data members declared as private are accessible only within the class in which they are
declared.
 Any other class of the same package will not be able to access these members.
 Top-level classes or interfaces cannot be declared as private because
 Private means “only visible within the enclosing class”.
 protected means “only visible within the enclosing class and any subclasses”

3. Protected Access Modifier


The protected access modifier is specified using the keyword protected.
The methods or data members declared as protected are accessible within the same package or
subclasses in different packages.

4. Public Access modifier


The public access modifier is specified using the keyword public.
 The public access modifier has the widest scope among all other access modifiers.
 Classes, methods, or data members that are declared as public are accessible from
everywhere in the program. There is no restriction on the scope of public data members.

Acharya Institute of Technology II sem


Object Oriented Programming using Java

/* In a class hierarchy, private members remain private to their class.


This program contains an error and will notcompile.
*/
// 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);
}
}

Output: Error (j is private, only class A can Access it)

Super class variables can refer sub-class object


o To a reference variable of a super class can be assigned a reference to any
subclassderived from that super class.
o When a reference to a subclass object is assigned to a super class reference
variable, we will have to access only to those parts of the object defined by the
super class
o It is bcz the super class has no knowledge about what a sub class adds to it.

Acharya Institute of Technology II sem


Object Oriented Programming using Java

Using super keyword

The super keyword in Java is a reference variable which is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly which is
referred by super reference variable.
Usage of Java super Keyword
 super can be used to refer immediate parent class instance variable.
 super can be used to invoke immediate parent class method.
 super() can be used to invoke immediate parent class constructor.

1) Super is used to refer immediate parent class instance variable.

We can use super keyword to access the data member or field of parent class. It is used if parent class
and child class have same fields.

Example 1:
package superKeyword;
public class SuperDemo
{
// Declare an instance variable and initialize value of the variable.
int x = 100;
}
public class Sub extends SuperDemo
{
// Declare an instance variable with the same name as provided the name of an instance variable in the
superclass.
int x = 200;
void display()
{
// Call superclass variable x. But, it will call variable x of class Sub because of the same name.
System.out.println("Value of variable of Sub: " +x); // Here, we have created an object of class Sub.
// Therefore, it will print the value of the variable of the class Sub.
// To call superclass instance variable, we will use the super keyword as a reference variable.
System.out.println("Value of variable of SuperDemo: " +super.x); // x of
class SuperDemo will call.
}
public static void main(String[] args)

Acharya Institute of Technology, Bangalore MCA


Object Oriented Programming using Java

{
Sub s = new Sub();
s.display();
}
}
Output:
Value of variable of Sub: 200

Value of variable of SuperDemo: 100

Example 2:
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
Output: black
White

2) super can be used to invoke parent class method


The super keyword can also be used to invoke parent class method. It should be used if subclass
contains the same method as parent class. In other words, it is used if method is overridden.

Example 1:

// Superclass definition
class QuadrilateralShape {
// Method to display the shape type

Acharya Institute of Technology, Bangalore MCA


Object Oriented Programming using Java

public void displayShapeType() {


System.out.println("I am a Quadrilateral");
}
}
// Subclass definition that extends the Superclass
class RectangularShape extends QuadrilateralShape {
// Method to display the shape type
public void displayRectangleType() {
System.out.println("I am a Rectangle");
}
// Method to display the shape types
public void displayShapeTypes() {
// This calls the subclass method (overriding method)
displayRectangleType();
// This calls the superclass method (overridden method)
super.displayShapeType();
}
}
class Main {
public static void main(String[] args) {
// Create an object of the RectangularShape class
RectangularShape r = new RectangularShape();
// Call the displayShapeTypes method
r.displayShapeTypes();
}}
Output:
I am a Rectangle
I am a Quadrilateral

Acharya Institute of Technology, Bangalore MCA


Object Oriented Programming using Java

Example 2:
class Animal{
void eat(){
System.out.println("eating...");
}
}
class Dog extends Animal{
void eat(){
System.out.println("eating bread...");
}
void bark(){
System.out.println("barking...");
}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
Output:
eating
barking

3) super is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor. Let's see a simple
example:

Example 1:
// Superclass definition
class Shape {
// Declare variables to store the dimensions
double dimension1, dimension2;

// Superclass (Shape) constructor


Shape(double dim1, double dim2) {
dimension1 = dim1;
dimension2 = dim2;
}
// Method to calculate the area of the shape
double calculateShapeArea() {

Acharya Institute of Technology, Bangalore MCA


Object Oriented Programming using Java

return dimension1 * dimension2;


}
}
// Subclass definition that extends the Superclass
class RectangularShape extends Shape {
// Subclass (RectangularShape) constructor
RectangularShape(double length, double breadth) {
// Call the superclass (Shape) constructor
super(length, breadth);
}
}
class Main {
public static void main(String[] args) {
// Create an object of the RectangularShape class
RectangularShape r = new RectangularShape(5, 8);
// Calculate and display the area of the shape
System.out.println("Area: " + r.calculateShapeArea());
}
}

Output: Area: 40.0

Example 2:
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
Output:
animal is created
dog is created

Acharya Institute of Technology, Bangalore MCA


Object Oriented Programming using Java

Calling members of super class using super

o The second form of super acts somewhat like this keyword, except that it always refers tothe
super class of the sub class in which it is used.
o The syntax is:
o Super.member ;
o Member can either be method or an instance variable

Program
// Using super to overcome namehiding.
class A {
int i;
}
// Create a subclass by extending class A. class B extends A {
int i; // this i hides the i in AB(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}
void show() {
System.out.println("i in superclass: " +
super.i);System.out.println("i in subclass: " +
i);
}
}
class UseSuper {
public static void
main(String args[]) { B
subOb = new B(1, 2);
subOb.show();
}
}
Output:
i in superclass: 1
i in subclass: 2

When the constructor called:

Always the super class constructor will be executed first and sub class constructor will beexecuted
last.

// Demonstrate when constructors are called.


// Create a super class. class A {
A() {

Acharya Institute of Technology, Bangalore MCA


Object Oriented Programming using Java

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

Using Final keyword:


As the word-final suggests, we can finalize a certain entity using the final keyword. In other words,
anything declared final in the java program cannot be modified. The final keyword restricts the
access of the user to modify the data.

The final keyword is a non-access modifier used for classes, attributes and methods, which makes
them non-changeable (impossible to inherit or override).
The final keyword is useful when you want a variable to always store the same value, like PI
(3.14159...). The final keyword is called a "modifier".

 A variable that is declared as a final variable is a constant throughout the program and its
value cannot be changed whatsoever.
 Method that is declared final cannot be overridden by any other subclasses.
 A class that is declared final cannot be inherited by any other class.

Example: // Example for final variable

class Bike9{
final int speedlimit=90;//final variable

Acharya Institute of Technology, Bangalore MCA


Object Oriented Programming using Java

void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class

Output: Compile Time Error

Example 2:
// Example of final method
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
Output: Compile Time Error

Example 3:
// Example of final class
final class Bike{}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
Output: Compile Time Error

Acharya Institute of Technology, Bangalore MCA


Object Oriented Programming using Java

Using final to Prevent Overriding:


Overriding is when a child class has its method implementation for the method already present in the
parent class.
Technically, overriding is a function that requires a subclass or child class to provide a variety of
method implementations, that are already provided by one of its superclasses or parent classes, in
any object-oriented programming language.
When a method in a subclass has the same name and signature as in its super-class, the subclass is
originated from the super-class.
One of the ways that Java manages Run Time Polymorphism is by method overriding.

All methods and variables can be overridden by default in a subclasses. If we need to prevent the
subclasses from overriding the members of the superclass, we can declare them final. Any attempt to
override a final method in a subclass results in the compile-time-error. Methods declared as final cannot
be overridden. The following fragment illustrates final:

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!");
}
}

Example 2:
class Parent {
final void fun() {
System.out.println("Parent Fun");
}}

class Child extends Parent{


//Compiler error
void fun() {
System.out.println("Child Fun");
}}

public class Demo {

public static void main(String[] args){


Parent obj = new Child();
obj.fun();
}
}

Acharya Institute of Technology, Bangalore MCA


Object Oriented Programming using Java

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. To prevent a class from being inherited, add final to class declaration.
Declaring a class as final declares all of its methods as final.
We cannot declare a class as both abstract and final since an abstract class has to be extended by
its subclasses.
Here is an example of a final class:
final class A {
// ...
}

// The following class is illegal.


class B extends A { // ERROR! Can't subclass A
// ...
}
As the comments imply, it is illegal for B to inherit A since A is declared as final.

Polymorphism
Polymorphism in Java is the task that performs a single action in different ways.
Polymorphism occurs when there is inheritance, i.e., many classes are related. The derivation of the
word Polymorphism is from two different Greek words- poly and morphs. “Poly” means numerous,
and “Morphs” means forms. So, polymorphism means innumerable forms.
Example:
class Shapes {
public void area() {
System.out.println("The formula for area of ");
}
}
class Triangle extends Shapes {
public void area() {
System.out.println("Triangle is ½ * base * height ");
}
}
class Circle extends Shapes {
public void area() {
System.out.println("Circle is 3.14 * radius * radius ");
}
}
class Main {
public static void main(String[] args) {

Acharya Institute of Technology, Bangalore MCA


Object Oriented Programming using Java

Shapes myShape = new Shapes(); // Create a Shapes object


Shapes myTriangle = new Triangle(); // Create a Triangle object
Shapes myCircle = new Circle(); // Create a Circle object
myShape.area();
myTriangle.area();
myShape.area();
myCircle.area();
}
}
Output:
The formula for the area of the Triangle is ½ * base * height
The formula for the area of the Circle is 3.14 * radius * radius

Binding: Connecting a method call to the method body is known as binding . There are two types
pf binding in Java:
1. Static Binding (also known as Early Binding).
2. Dynamic Binding (also known as Late Binding).

Look at the below figure in which we have defined a class X. It has two methods m1() and
m2(). The x.m1(); (method call) is linked with m1() method whereas, x.m2(); is linked with
m2() method. This linking is called binding.

Static binding:
When type of the object is determined at compiled time (by the compiler), it is known as static
binding. If there is any private, final or static method in a class, there is static binding.
Java compiler just checks which method is going to be called through reference variable
and method definition exists or not.

Acharya Institute of Technology, Bangalore MCA


Object Oriented Programming using Java

This binding is also known as early binding because it takes place before the program actually
runs. An example of static binding is method overloading.

Example1:
package methodOverloading;
public class Addition
{
void add(int x, int y)
{
int sum = x + y;
System.out.println("Sum of two numbers: " +sum);
}
void add(int x, int y, int z)
{
int sum = x + y + z;
System.out.println("Sum of three numbers: " +sum);
}
public static void main(String[] args)
{
Addition a = new Addition();
a.add(10, 20); // Calling add() method with passing two argument values.
a.add(20, 30, 40); // Calling add() method with passing three argument values.
}
}
Output:
Sum of two numbers: 30
Sum of three numbers: 90

In the above preceding code, Java compiler did not check the type of object. It just checked only
method call through reference variable and method definition.

Example 2:
package MCA;
class Person
{
public void speak()
{
System.out.println("Person speaks");
}
}
class Teacher extends Person
{

Acharya Institute of Technology, Bangalore MCA


Object Oriented Programming using Java

public static void speak()


{
System.out.println("Teacher speaks");
}
}
public class StaticBinding
{
public static void main( String args[ ])
{
// Reference is of Person type and object is Teacher type
Person obj = new Teacher();
obj.speak();
//Reference and object both are of Person type.
Person obj2 = new Person();
obj2.speak();
}
}
Output:
Person speaks
Person speaks

From the above code, we got the same output from the parent class. This happened because:
 The reference for the parent class and the child class is the same(Person). That is, a single
object refers to both of them.
 Since the method is static, the compiler is aware that this method can not be overridden in the
child class and it knows which method to call. Therefore there is no ambiguity and the output
is the same for both cases.

Dynamic binding:
The binding which occurs during runtime is called dynamic binding in java. This binding is
resolved based on the type of object at runtime. In dynamic binding, the actual object is used for
binding at runtime.
Dynamic binding is also called late binding or runtime binding because binding occurs during
runtime. An example of dynamic binding is method overriding.
Let’s take an example program based on dynamic binding in Java.
Example 1:
package dynamicBinding;
public class Animal
{
void eat()
{
System.out.println("Animals eat both plants and flesh");

Acharya Institute of Technology, Bangalore MCA


Object Oriented Programming using Java

}
}
public class Lion extends Animal
{
void eat()
{
System.out.println("Lions eat flesh because they are carnivore");
}
}
public class DynamicBindingTest
{
public static void main(String[] args)
{
Animal a = new Animal();
a.eat(); // It will call eat() method of Animal class because the reference variable is pointing to
object of animal class.
Animal a1 = new Lion();
a1.eat(); // It will call eat() method of Lion class because the reference variable is pointing
towards the object of Loin class.
}
}
Output:
Animals eat both plants and flesh
Lions eat flesh because they are carnivore

Example 2:
package MCA;
class Person
{
public void speak()
{
System.out.println("Person speaks");
}
}
class Teacher extends Person
{
@Override
public void speak()
{
System.out.println("Teacher speaks");
}

Acharya Institute of Technology, Bangalore MCA


Object Oriented Programming using Java

}
public class DynamicBinding
{
public static void main( String args[])
{
//Reference and objects are of Person type.
Person obj2 = new Person();
obj2.speak();
// Reference is of Person type and object is Teacher type
Person obj = new Teacher();
obj.speak();
}
}
Output:
Person speaks
Teacher speaks

Method overriding:
 In a class hierarchy, when a method in a sub class has the same name and type signature as a
method in its super class, then the method in the sub class is said to be override the method in
the sub class.
 When an overridden method is called from within a sub class, it will always refers to the version
of that method defined by the sub class.
 The version of the method defined in the super class is hidden.
 In this situation, first it checks the method is existed in super class are not. If it is existed then

Acharya Institute of Technology, Bangalore MCA


Object Oriented Programming using Java

it executes the version of sub class otherwise it gives no such method foundexception.

Example:
class Human{
//Overridden method
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
//This will call the child class version of eat()
obj.eat();
}
}
Dynamic method dispatch
Method Overriding is an example of runtime polymorphism. When a parent class reference
points to the child class object then the call to the overridden method is determined at runtime,
because during method call which method(parent class or child class) is to be executed is
determined by the type of object. This process in which call to the overridden method is resolved
at runtime is known as dynamic method dispatch. Lets see an example to understand this:
Example:
class ABC{
//Overridden method
public void disp()
{
System.out.println("disp() method of parent class");
}
}
class Demo extends ABC{
//Overriding method
public void disp(){
System.out.println("disp() method of Child class");
}
public void newMethod(){
System.out.println("new method of child class");

Acharya Institute of Technology, Bangalore MCA


Object Oriented Programming using Java

}
public static void main( String args[]) {
/* When Parent class reference refers to the parent class object
* then in this case overridden method (the method of parent class)
* is called.
*/
ABC obj = new ABC();
obj.disp(); /* When parent class reference refers to the child class object
* then the overriding method (method of child class) is called.
* This is called dynamic method dispatch and runtime polymorphism
*/
ABC obj2 = new Demo();
obj2.disp();
}
}
Output:
disp() method of parent class
disp() method of Child class

Abstract classes and Methods:


o The abstract class in Java cannot be instantiated (we cannot create objects of abstract classes).
We use the abstract keyword to declare an abstract class.
o An abstract class is class that has at least one abstract method. For example,

// create an abstract class


abstract class Language {
// fields and methods
}
...
// try to create an object Language
// throws an error
Language obj = new Language();

Example:
abstract class Language {
// method of abstract class
public void display() {
System.out.println("This is Java Programming");
}
}
class Main extends Language {
public static void main(String[] args) {
Main obj = new Main();

Acharya Institute of Technology, Bangalore MCA


Object Oriented Programming using Java

// access method of abstract class


// using object of Main class
obj.display();
}
}
Output:
This is java programming
An abstract class can have both the regular methods and abstract methods. For example,
abstract class Language {
// abstract method
abstract void method1();
// regular method
void method2() {
System.out.println("This is regular method");
}
}

Example of Abstract Methods:


abstract class Animal {
abstract void makeSound();

public void eat() {


System.out.println("I can eat.");
}
}
class Dog extends Animal {
// provide implementation of abstract method
public void makeSound() {
System.out.println("Bark bark");
}
}
class Main {
public static void main(String[] args) {
// create an object of Dog class
Dog d1 = new Dog();
d1.makeSound();
d1.eat();
}
}
Output:
Bark bark
I can eat

Acharya Institute of Technology, Bangalore MCA


Object Oriented Programming using Java

Example 2:
abstract class Multiply {
// abstract methods
// sub class must implement these methods
public abstract int MultiplyTwo (int n1, int n2);
public abstract int MultiplyThree (int n1, int n2, int n3);

// regular method with body


public void show() {
System.out.println ("Method of abstract class Multiply");
}
}
// Regular class extends abstract class
class AbstractMethodEx1 extends Multiply {

// if the abstract methods are not implemented, compiler will give an error
public int MultiplyTwo (int num1, int num2) {
return num1 * num2;
}
public int MultiplyThree (int num1, int num2, int num3) {
return num1 * num2 * num3;
}

// main method
public static void main (String args[]) {
Multiply obj = new AbstractMethodEx1();
System.out.println ("Multiplication of 2 numbers: " + obj.MultiplyTwo (10, 50));
System.out.println ("Multiplication of 3 numbers: " + obj.MultiplyThree (5, 8, 10));
obj.show();
}
}
Output:
Multiplication of 2 numbers: 500
Multiplication of 3 numbers: 400
Method of abstract class Multiply

Acharya Institute of Technology, Bangalore MCA

You might also like