Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
59 views

Implementing Inheritance and Polymorphism

Java inheritance allows classes to inherit features from other classes. It supports code reusability and abstraction. There are different types of inheritance in Java including single, multilevel, and hierarchical inheritance. Abstract classes can be used to define common behaviors to be implemented in subclasses through method overriding, which is an example of dynamic polymorphism in Java.

Uploaded by

Pramod kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views

Implementing Inheritance and Polymorphism

Java inheritance allows classes to inherit features from other classes. It supports code reusability and abstraction. There are different types of inheritance in Java including single, multilevel, and hierarchical inheritance. Abstract classes can be used to define common behaviors to be implemented in subclasses through method overriding, which is an example of dynamic polymorphism in Java.

Uploaded by

Pramod kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Implement inheritance

Java, Inheritance is an important pillar of


OOP(Object-Oriented Programming). It is the
mechanism in Java by which one class is allowed
to inherit the features(fields and methods) of
another class.

In Java, Inheritance means creating new classes


based on existing ones. A class that inherits
from another class can reuse the methods and
fields of that class. In addition, you can add new
fields and methods to your current class as
well.
Why Do We Need Java Inheritance?

Code Reusability: The code written in the


Superclass is common to all subclasses. Child
classes can directly use the parent class
code.
Method Overriding: Method Overriding is
achievable only through Inheritance. It is
one of the ways by which Java achieves Run
Time Polymorphism.
Abstraction: The concept of abstract
where we do not have to provide all details is
achieved through inheritance. Abstraction
only shows the functionality to the user.
Important Terminologies Used in
Java Inheritance
Super Class/Parent Class: The class whose
features are inherited is known as a superclass(or
a base class or a parent class).

Sub Class/Child Class: The class that inherits


the other class is known as a subclass(or a
derived class, extended class, or child class). The
subclass can add its own fields and methods in
addition to the superclass fields and methods.

Reusability: Inheritance supports the concept of


“reusability”, i.e. when we want to create a new
class and there is already a class that includes
some of the code that we want, we can derive our
new class from the existing class. By doing this,
we are reusing the fields and methods of the
existing class.
Types of Inheritance
Java supports the following types of
inheritance:

 Single level inheritance


 Multilevel inheritance
 Hierarchical inheritance
Single Level Inheritance
In single level inheritance, a single subclass
derives the functionality of an existing
superclass. The following figure explains the
concept of single level inheritance.

In the preceding figure, there are two classes,


Person and Employee. The class, Employee, is the
subclass that is inherited from the superclass,
Person.
Multilevel Inheritance
In multilevel inheritance, a subclass inherits the properties
of another subclass. The following figure explains the
concept of multilevel inheritance.

In the preceding figure, the class, Person, is a superclass


for the class, Employee, and the class, Employee, is a
superclass of the class, Manager. You can include any
number of levels in multilevel inheritance.
Hierarchical Inheritance
In hierarchical inheritance, one or more subclasses are
derived from a single superclass. The following figure
shows the concept of hierarchical inheritance.

In the preceding figure, the subclasses, Employee and


Student, inherit the properties of a single superclass,
Person.
How to Use Inheritance in Java?

The extends keyword is used for


inheritance in Java. Using the extends
keyword indicates you are derived from an
existing class. In other words, “extends”
refers to increased functionality.

Syntax :
class derived-class extends base-class
{
//methods and fields
}
Inheriting a Class
Inheritance signifies the relationship between a
superclass and its subclass. In order to inherit a
class, you need to use the extends keyword.

For example,
if you have a superclass named Books and a
subclass named PaperBooks that share common
functionalities and properties with the
superclass, such as printing the book details and
author name, total number of pages, and price.

In order to implement single level inheritance


for the Books class, you can use the following
code:
class Books
{
int page_num;
String authorname, name; float price;
public Books()
{
page_num = 50;
authorname = "Andrew Jones";
name = "The Living Ideas";
price = 15.78f;
}

public void displayInfo()


{
System.out.println("The name of the book is " + name);
System.out.println("The price of the book is " + price);
System.out.println("The author name is " + authorname);
System.out.println("The total number of pages is " + page_num)
}
}
class PaperBooks extends Books
{
int shippingcharges = 10;

public void printInfo()


{
displayInfo();//Calling the method of Book class.
System.out.println("The total shipping charges are" +
shippingcharges);
}

public static void main(String[] args)


{
PaperBooks pb = new PaperBooks();
pb.printInfo();
}
} // End of class

In the preceding code, PaperBooks is a subclass of


the superclass class, Books. The subclass uses the
various properties, such as author name and price.
In addition, it uses the displayInfo() method.
Implementing Polymorphism
Polymorphism is an OOP feature that enables an entity
to exist in multiple forms. In Java, polymorphism has
the following two types:

 Static polymorphism
 Dynamic polymorphism

Static Polymorphism
In case of static polymorphism, an entity, such as a
method, can exist in multiple forms. This means that
one or more methods can exist with the same name
but with a different argument list. This type of
polymorphism, when exhibited by methods, is known as
method overloading.

For example, a method named calculate can be


overloaded by using the following code snippet:
calculate( int x, int y)
{
/* Some code to be added */
}

calculate (float x, int y, int z)


{
/* Some code to be added */
}

calculate (int x, float y)


{
/* Some code to be added */
}

calculate (float y, int x)


{
/* Some code to be added */
}
In the preceding code snippet, the calculate()
method implements polymorphism by existing in
multiple forms. Each of the forms of the calculate()
method differs from the other in terms of method
signature. During compilation, the compiler will bind
the function call.

For example, calculate (0.75,8,10) with the calculate


(float x, int y, int z) method. Whereas, the compiler
will bind the calculate (81,102), statement to the
calculate(int x, int y) method.

While implementing method overloading, it is


important to consider the following points about
overloaded methods:
 They differ in the type and/or number of their
arguments.
 They differ in the sequence of their parameters.
 They differ in the data types of their
parameters.
Dynamic Polymorphism
In Java, if a superclass and subclass contain
methods with the same name, the version to be
invoked will be decided by the JVM at runtime.
Such a decision to invoke the appropriate
method is known as dynamic polymorphism.

Dynamic polymorphism is implemented in Java


by method overriding. Method overriding
enables a subclass to provide its own
implementation of a method that already has an
implementation defined in its superclass. To
override a method present in the superclass,
the subclass method should have the same
name, same parameters, and same return type
as the method in the superclass.
class Person
{

public void showDetails()


{
System.out.println("In the Person class");
}
}
class Employee extends Person
{
public void showDetails()
{
System.out.println("In the Employee class");
}
}
class Student extends Person
{
public void showDetails()
{
System.out.println("In the Student class");
}
}
class Method_Override
{
public static void main(String args)
{
Person P = new Person();
Employee E = new Employee();
Student S = new Student();
Person ref;
ref = P;
ref.showDetails(); // calls the showDetails method of the
//Person class
ref = E;
ref.showDetails(); // calls the showDetails method of the
//Employee class
ref = S;
ref.showDetails();// calls the showDetails method of the
//Student class
} // end of main()
} // end of class
It is important to consider the following points
while implementing overriding:

 Private methods cannot be overridden, as


they are not accessible in subclasses.

 Final methods cannot be overridden.

 An overridden method cannot be granted


more restrictive access rights in a subclass
than it is assigned in case of a superclass.
For example, if a method is specified with
the public access specifier in a superclass, it
cannot be specified as protected in a
subclass.
Abstract class
Inheritance can also be implemented by using abstract
classes. An abstract class is a class that contains one or
more abstract methods.

An abstract class cannot be instantiated but can be


inherited by other classes by using the extends keyword.

When an abstract class is inherited by a subclass, the


subclass must provide the implementation of all the
abstract methods defined in the abstract class.

The abstract class acts as a blueprint for other classes.


You can define an abstract class by using the following
syntax:

<access_specifier> abstract class <abstract_class_name>


{
//variables
// abstract and concrete methods
}
In the preceding syntax, <access_specifier>
specifies the access specifiers, such as public and
private. abstract and class are keywords.
<abstract_class_name> specifies the name of the
abstract class.

You can declare an abstract method by using the


following syntax:

abstract return-type methodname(parameter-list);


In the preceding syntax, abstract is a keyword.
return-type specifies the type of value returned by
the method. methodname specifies the name of the
method and parameter-list specifies the list of the
parameters that can be accepted by the method.
Consider the scenario of a game console. Each of the
games in the game console must offer functionalities to
play the game, compute the score, display the score, and
exit the game. However, some of these functionalities,
such as play the game and compute the score, will vary for
every game. However, some of the functionalities, such as
display the score and exit the game, will remain the same
for all the games.
For example,
the Badminton game will have a different mechanism to
compute the score in comparison to the TableTennis game.
However, both the games will display the score in a similar
manner. Therefore, for the game console, you can create
an abstract class named GameConsole. This class will
contain concrete methods for the functionalities that are
common to all the games, such as displayScore(). The
functionalities that need to be implemented differently
by every game, such as computeScore(), will be declared
as abstract methods. Therefore, the game classes, such
as Badminton, which will inherit the GameConsole class,
will provide the implementation of these abstract
methods.
abstract class GameConsole
{
int score;
void displayScore()
{
System.out.println("The displayScore method.");
}
abstract void computeScore(); abstract void playGame();
}
class Badminton extends GameConsole
{
void playGame()
{
System.out.println("Starting the Badminton Game...");
}
void computeScore()
{
System.out.println("Implementing the abstract method of the
Gameconsole class.");
}
}

class GameDemo
{
public static void main(String args[])
{
Badminton obj1 = new Badminton();
obj1.playGame();
obj1.computeScore();
obj1.displayScore();
}
}
this keyword
Sometimes, within a method or a constructor,
there may be a need to refer to the object that
has invoked it. Moreover, in your program,
sometimes you may have a requirement where the
class variables and the method or constructor
variables have the same name.

In order to cater to the preceding requirements,


Java provides the this keyword. In addition, it
helps to differentiate between the member and
the local variables of a method or constructor in
case the member and the local variables of a
method have the same name. For example, consider
the following code:
class Vehicle
{
int max_speed = 210;
Vehicle(int max_speed)
{
max_speed = max_speed;
}
public void showmaxspeed()
{
System.out.println("The top speed is " +
max_speed);
}
}

class MainClass
{
public static void main(String args[])
{
Vehicle a = new Vehicle(250);
a.showmaxspeed();
}
}
In the preceding code, the member variable and the
parameter for the constructor of Vehicle share the
same name, max_speed.
In such a scenario, when the object, a, is created, the
value, 250, is assigned to it.
However, when the showmaxspeed() method is invoked,
the value of the class variable, max_speed, is displayed
as 210.
This is because the member variable is hidden by the
parameter of the constructor.

To overcome this problem, you can access the member


variable by using the following code snippet:

Vehicle (int max_speed)


{
this.max_speed = max_speed;
}
super keyword in Java
The super keyword in java is a reference variable that is
used to refer to parent class objects.

The keyword “super” came into the picture with the


concept of Inheritance. It is majorly used in the following
contexts:
 Use of super with variables
 Use of super with methods
 Use of super with constructors

Characteristics of super keyword:


In Java, the super keyword is used to refer to the parent
class of a subclass. Here are some of its characteristics:

 super is used to call a superclass constructor: When a


subclass is created, its constructor must call the
constructor of its parent class. This is done using the
super() keyword, which calls the constructor of the
parent class.
super is used to call a superclass method: A subclass can
call a method defined in its parent class using the super
keyword. This is useful when the subclass wants to invoke
the parent class‟s implementation of the method in
addition to its own.
super is used to access a superclass field: A subclass can
access a field defined in its parent class using the super
keyword. This is useful when the subclass wants to
reference the parent class‟s version of a field.
super must be the first statement in a constructor:
When calling a superclass constructor, the super()
statement must be the first statement in the
constructor of the subclass.
super cannot be used in a static context: The super
keyword cannot be used in a static context, such as in a
static method or a static variable initializer.
super is not required to call a superclass method: While
it is possible to use the super keyword to call a method in
the parent class, it is not required. If a method is not
overridden in the subclass, then calling it without the
super keyword will invoke the parent class‟s
implementation.
Overall, the super keyword is a powerful tool for
1 Use of super with variables
This scenario occurs when a derived class and base
class has the same data members. In that case, there
is a possibility of ambiguity for the JVM. We can
understand it more clearly using this code snippet:
// Java code to show use of super keyword with
variables Base class vehicle
class Vehicle {
int maxSpeed = 120;
}
// sub class Car extending vehicle
class Car extends Vehicle {
int maxSpeed = 180;

void display()
{
// print maxSpeed of base class (vehicle)
System.out.println("Maximum Speed: "+
super.maxSpeed);
}
}
// Driver Program

class Test
{
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}

Output
Maximum Speed: 120

In the above example, both base class and


subclass have a member maxSpeed. We could
access maxSpeed of base class in subclass using
super keyword.
2. Use of super with methods
This is used when we want to call the parent class method.

So whenever a parent and child class have the same-named


methods then to resolve ambiguity we use the super
keyword. This code snippet helps to understand the said
usage of the super keyword.

// Java program to show use of super with methods

// superclass Person
class Person {
void message()
{
System.out.println("This is person class\n");
}
}
// Subclass Student
class Student extends Person {
void message()
{
System.out.println("This is student class");
}
void display()
{
// will invoke or call current class message()
method
message();
// will invoke or call parent class message() method
super.message();
}
}
class Test {
public static void main(String args[])
{
Student s = new Student();
// calling display() of Student
s.display();
}
}
Output
This is student class
This is person class

In the above example, we have seen that if we only call


method message() then, the current class message() is
invoked but with the use of the super keyword,
message() of superclass could also be invoked.
3. Use of super with constructors

The super keyword can also be used to access the parent


class constructor. One more important thing is that
„super‟ can call both parametric as well as non-parametric
constructors depending upon the situation. Following is
the code snippet to explain the above concept:

// Java Code to show use of super keyword with


Constructor

// superclass Person

class Person
{
Person()
{
System.out.println("Person class Constructor");
}
}
// subclass Student extending the Person class
class Student extends Person
{
Student()
{
// invoke or call parent class constructor
super();

System.out.println("Student class Constructor");


}
}

// Driver Program
class Test
{
public static void main(String[] args)
{
Student s = new Student();
}
}
Output
Person class Constructor
Student class Constructor

In the above example, we have called the superclass


constructor using the keyword „super‟ via subclass
constructor.
Advantages:
The super keyword in Java provides several
advantages in object-oriented programming:
Enables reuse of code: Using the super keyword
allows subclasses to inherit functionality from
their parent classes, which promotes reuse of
code and reduces duplication.
Supports polymorphism: Because subclasses can
override methods and access fields from their
parent classes using super, polymorphism is
possible. This allows for more flexible and
extensible code.
Provides access to parent class behavior:
Subclasses can access and use methods and fields
defined in their parent classes through the super
keyword, which allows them to take advantage of
existing behavior without having to reimplement
it.
Allows for customization of behavior: By
overriding methods and using super to call
the parent implementation, subclasses can
customize and extend the behavior of their
parent classes.

Facilitates abstraction and encapsulation:


The use of super promotes encapsulation
and abstraction by allowing subclasses to
focus on their own behavior while relying on
the parent class to handle lower-level
details.

Overall, the super keyword is a key feature


of inheritance and polymorphism in Java,
and it provides several benefits for
developers seeking to write reusable,
extensible, and well-organized code.
Important Points to Remember while using Super
Keyword
 Call to super() must be the first statement in
the Derived(Student) Class constructor because
if you think about it, it makes sense that the
superclass has no knowledge of any subclass, so
any initialization it needs to perform is separate
from and possibly prerequisite to any
initialization performed by the subclass.
Therefore, it needs to complete its execution
first.
 If a constructor does not explicitly invoke a
superclass constructor, the Java compiler
automatically inserts a call to the no-argument
constructor of the superclass. If the superclass
does not have a no-argument constructor, you
will get a compile-time error. The
object does have such a constructor, so if the
Object is the only superclass, there is no
problem.
 If a subclass constructor invokes a constructor
of its superclass, either explicitly or implicitly,
you might think that a whole chain of
constructors is called, all the way back to the
constructor of Object. This, in fact, is the
case. It is called constructor chaining.
Interface in JAVA
An interface in Java is a blueprint of a class. It
has static constants and abstract methods.

The interface in Java is a mechanism to


achieve abstraction. There can be only abstract
methods in the Java interface, not method body.

It is used to achieve abstraction and


multiple inheritance in Java.

In other words, you can say that interfaces can


have abstract methods and variables. It cannot
have a method body.

Java Interface also represents the IS-A


relationship.
 It cannot be instantiated just like the abstract
class.
 Since Java 8, we can have default and static
methods in an interface.
 Since Java 9, we can have private methods in an
interface.
Why use Java interface?

There are mainly three reasons to use interface. They


are given below.

 It is used to achieve abstraction.


 By interface, we can support the functionality of
multiple inheritance.
How to declare an interface?
An interface is declared by using the interface
keyword. It provides total abstraction; means all the
methods in an interface are declared with the empty
body, and all the fields are public, static and final by
default. A class that implements an interface must
implement all the methods declared in the interface.

Syntax:

interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}
Internal addition by the compiler
The Java compiler adds public and abstract keywords
before the interface method.

Moreover, it adds public, static and final keywords


before data members.

In other words, Interface fields are public, static and


final by default, and the methods are public and
abstract.
The relationship between classes and
interfaces
As shown in the figure given below, a class
extends another class, an interface extends
another interface, but a class implements an
interface.
Java Interface Example: Bank

interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}

class PNB implements Bank{


public float rateOfInterest(){return 9.7f;}
}

class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
} //End of Main()
} //End of Class
Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an


interface extends multiple interfaces, it is
known as multiple inheritance.
interface Printable{
void print();
}
interface Showable{
void show();
}
class Multiple implements Printable , Showable
{
public void print()
{System.out.println("Hello");}
public void show()
{System.out.println("Welcome");}

public static void main(String args[])


{
Multiple obj = new Multiple();
obj.print();
obj.show();
}
}
Interface inheritance
A class implements an interface, but one interface
extends another interface.

interface Printable{
void print();
}

interface Showable extends Printable{


void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}
final Keyword in Java
final keyword is used in different
contexts. First of all, final is a non-access
modifier applicable only to a variable, a
method, or a class. The following are
different contexts where final is used.
1. Java final Variable
When a final keyword is used with a variable, it makes the
variable constant. Hence, once assigned, the value of the
variable cannot be changed.

Let‟s understand using an example.

class Circle {
public static void main(String[] args) {
// Constant variable to store the value of pi
static final double PI = 3.14;

// Radius of the circle


int radius = 4;

// Calculate and display the area of the circle


System.out.println("Area of circle: " + (PI * radius *
radius));
}
}
Final Keyword with Methods
A final method cannot be overridden or hidden by
subclasses which means even though a subclass can
call the final method of parent class without any
issues but it cannot override it.

This is used to prevent unexpected behavior from


a subclass altering a method that may be crucial to
the function or consistency of the class. We must
declare methods with the final keyword for which
we required to follow the same implementation
throughout all the derived classes.

The main intention of making a method final would


be that the content of the method should not be
changed by any outsider.
Example : Final Methods in Java
class Bike
{
final void run()
{
System.out.println ("running");
}
}
class Honda extends Bike
{
void run()
{
// COMPILE-ERROR! Can't override.
System.out.println ("running safely with 100kmph");
}

public static void main (String args[])


{
Honda honda = new Honda ();
honda.run();
}
}
Final Class in Java
In Java, the final class cannot be inherited by
another class.

The main purpose of using a class being


declared as final is to prevent the class from
being subclasses.

If a class is marked as final then no class can


inherit any feature from the final class.
Example to demonstrate Final Class in Class:
final class FinalClass
{
// create a final method
public void display ()
{
System.out.println ("This is a final method.");
}
}
class Main extends FinalClass
{
// try to override final method
public void display ()
{
System.out.println ("The final method is overridden.");
}

public static void main (String[]args)


{
Main obj = new Main ();
obj.display ();
}
}

You might also like