0% found this document useful (0 votes)
2 views40 pages

MCA Java Programming Unit 4 Inheritance and Polymorphism

This self-learning material covers the concepts of inheritance and polymorphism in Java, fundamental to object-oriented programming. It explains various types of inheritance, such as single, multilevel, hierarchical, and multiple inheritance, along with the principles of polymorphism, including static and dynamic polymorphism. Additionally, it discusses the use of abstract and final keywords, interfaces, and access modifiers in Java programming.

Uploaded by

surajpawar0229
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)
2 views40 pages

MCA Java Programming Unit 4 Inheritance and Polymorphism

This self-learning material covers the concepts of inheritance and polymorphism in Java, fundamental to object-oriented programming. It explains various types of inheritance, such as single, multilevel, hierarchical, and multiple inheritance, along with the principles of polymorphism, including static and dynamic polymorphism. Additionally, it discusses the use of abstract and final keywords, interfaces, and access modifiers in Java programming.

Uploaded by

surajpawar0229
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

Java Programming

Inheritance
and
Polymorphism
SELF LEARNING MATERIAL

SEM - I (103)

MCA
UNIT-4 INHERITANCE AND POLYMORPHISM
TABLE OF CONTENTS

4.1 Introduction
4.2 Inheritance
4.3 Types of Inheritance
4.4 Polymorphism
4.5 Abstract and Final Keywords
4.6 Interfaces
4.7 Access Modifiers
4.8 Method Access Modifiers
4.9 Summary
4.10 Case Study
4.11 Terminal Questions
4.12 Answers
4.13 Assignment
4.14 References

Learning Objectives
• To define the concept of Inheritance and Polymorphism
• To learn theuse of abstract and final keywords
• To understand the concept of Interfaces
NOTES

4.1
Introduction
Inheritance and polymorphism in Java are fundamental concepts that have
their roots in object-oriented programming (OOP) principles and the history
of programming languages.

Java was designed as an object-oriented programming language and


inherited many concepts and syntax from its predecessors, including the
concept of inheritance. Java’s syntax for class declaration and the use of the
“extends” keyword to specify inheritance were inspired by C++, another
influential programming language. The idea of polymorphism dates back to
the 1970s and was popularized by languages like Simula and Smalltalk.

Java’s support for inheritance and polymorphism was a deliberate design


choice to promote code reuse, modularity, and flexibility. By embracing these
principles, Java encourages developers to create reusable and extensible
code, leading to more efficient and maintainable software development.

Since its release, Java has become one of the programming languages
with the highest usage rates, with inheritance and polymorphism playing
a crucial role in its success. These concepts have become cornerstones
of Java’s object-oriented programming paradigm and are widely used in
software development to create robust and scalable applications.

01
NOTES 4.2
Inheritance
In object-oriented programming (OOP), A class
can inherit traits and behaviors from another class STUDY NOTE
thanks to the fundamental idea of inheritance. It Inheritance creates a
promotes code reuse and facilitates the formation hierarchical structure
of class hierarchies, where more specific classes among classes, forming
inherit traits from more general classes. a tree-like relationship.
Each class (except for
Between classes, inheritance creates a “is-a”
the root class) has a
relationship. The word “superclass” or “base
single superclass and
class” refers to the class from which the subclass
may have one or more
inherits, whereas “subclass” or “derived class”
subclasses.
refers to the class that obtains attributes and
behaviours through inheritance. A class can
inherit traits and behaviors from another class thanks to the fundamental idea of
inheritance.

The flexibility to build specialized classes and code reuse are the main advantages
of inheritance that inherit and extend the functionality of more general classes.
By inheriting from a superclass, a subclass automatically inherits its fields and
methods, reducing code duplication and promoting modularity. This simplifies
the development process, as developers can build upon existing classes without
starting from scratch.

Inheritance in Java is implemented via the “extends” keyword. A subclass is declared


by specifying the superclass it extends, and it can further add its own additional
members or override inherited members to provide specialized implementations.
Using the proper access modifiers, the subclass has access to the superclass’s
inherited members.

Fig 1: Inheritance

02
Consider the following program:
NOTES
// Superclass
class Animal {
String name;
void eat() {
[Link](name + “ is eating.”);
}
}
// Subclass
class Dog extends Animal {
void bark() {
[Link](name + “ is barking.”);
}
}
public class InheritanceExample {
public static void main(String[] args) {
// Create an instance of the Dog class
Dog dog = new Dog();
[Link] = “Max”;
// Call methods from the superclass and subclass
[Link](); // Inherited from Animal class
[Link](); // Defined in Dog class
}
}

The program outputs:


Max is eating.
Max is barking.

This example of the ‘Dog’ class showcases the inheritance of the ‘name’ field and
the ‘eat()’ method from the ‘Animal’ [Link] subclass ‘Dog’ can then add its own
unique behaviour by defining the ‘bark ()’ method. Inheritance allows allowing us
to construct code by reusing the superclass’s specialized classes with additional
functionality.

Some definitions of inheritance by different authors are given below:

“Inheritance is the mechanism for automatic and controlled reuse of components


and classes.”
Grady Booch

“Inheritance is the process by which one object acquires the properties and
behaviour of another object of a different class.”
James Gosling, Bill Joy, and Guy Steele

03
NOTES CHECK YOUR PROGRESS
1. The class from which properties and behaviours are inherited is called the
______ class.
Fill in the blanks in the below code:
class Animal {
protected String name;
public Animal(String name) {
[Link] = name;
}
public void speak() {
[Link](“The animal speaks.”);
}
}
class Dog ______ Animal { // Blank #2
public Dog(String name) {
super(name);
}
public void speak() {
[Link](“The dog barks.”);
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Animal(“Generic Animal”);
Dog dog = new ____(“Buddy”);// Blank #3
[Link]();
[Link]();
[Link]([Link]);
[Link]([Link]);
}
}

Activity
Suppose you are developing a software system for a zoo. The system needs
to handle different types of animals present in the zoo, such as mammals,
birds, and reptiles. Each animal has common properties like name and age, but
they also have unique behaviours based on their species. You decide to use
inheritance to model the animal hierarchy in your system. Using inheritance in
Java, how would you design the classes to represent the animal hierarchy in the
zoo system? Create a hierarchy and facilitate a discussion with other students
in the class.

04
4.3 NOTES
Types of Inheritance

Different types of inheritance can be used in the Java programming language to


create links between classes.

Single Inheritance:
Using a single inheritance, a subclass derives from a single superclass. There can
only be one direct superclass for a class under this sort of inheritance. For example:

class Superclass {
// Superclass implementation
}
class Subclass extends Superclass {
// Subclass implementation
}

Multilevel Inheritance:
Multilevel inheritance refers to a chain of inheritance where a subclass becomes
the superclass for another class. This allows for creating a hierarchical relationship
between classes. For example:

class Animal {
// Animal implementation
}
class Mammal extends Animal {
// Mammal implementation
}
class Dog extends Mammal {
// Dog implementation
}

Hierarchical Inheritance:
Hierarchical inheritance involves multiple subclasses inheriting from a single
superclass. It allows for creating a class hierarchy where subclasses share common
properties and behaviours from a common superclass. For example:

class Shape {
// Shape implementation
}
class Circle extends Shape {
// Circle implementation
}
class Rectangle extends Shape {
// Rectangle implementation
}
05
NOTES Multiple Inheritance:
In a chain of inheritance known as multiple inheritance, one class becomes the
superclass for another. This makes it possible to
structure classes hierarchically. Java supports STUDY NOTE
various interfaces, which a class can inherit
Java does not support
multiple sets of behaviours. For example:
class-based multiple
interface Flyable { inheritance. Interfaces
void fly (); are used to do this.
}
interface Swimmable {
void swim ();
}
class Bird implements Flyable {
// Bird implementation
}
class Fish implements Swimmable {
// Fish implementation
}
class Duck implements Flyable, Swimmable {
// Duck implementation
}

CHECK YOUR PROGRESS


4. You are developing a banking application that needs to handle several bank
accounts, including savings accounts, checking accounts, and credit card
accounts. Each type of account has common properties like account number
and balance, but they also have specific functionalities based on their
account type. You decide to use hierarchical inheritance to model the bank
account hierarchy in your application. Using hierarchical inheritance in Java,
how would you design the classes to represent the bank account hierarchy
in the banking application?
5. Multilevel inheritance allows for creating a chain of inheritance where a
subclass becomes the superclass for another class. [True/False]
6. Multiple inheritance in Java is achieved by using the “extends” keyword for
multiple superclasses. [True/False]
7. If a class does not explicitly specify a superclass, it implicitly inherits from
the ___________ class.

Activity
Divide participants into groups. Assign each group one type of inheritance. Each
group should create a visual representation (diagram or flowchart) illustrating the
assigned type of inheritance. Each group should also provide real-life examples
or scenarios to demonstrate the concept clearly.

06
4.4 NOTES
Polymorphism

The capacity to view items as belonging to a


single superclass even though they are of distinct STUDY NOTE
classes or interface is made possible by the Polymorphism is derived
fundamental idea of polymorphism in object- from the Greek word’s
oriented programming. It allows for the utilization “poly” meaning “many”
of a unified interface to represent various object and “morphe” meaning
types, enhancing the flexibility and extensibility of “forms.” It describes
the code. an object’s capacity to
assume many shapes
Polymorphism allows methods to be written that
or exhibit various
can work with objects of different classes but
behaviours under
produce different results based based on the
various conditions.
object’s actual type at the moment of use. It allows
for method overriding and method overloading,
which are two key mechanisms for achieving polymorphism.

Types of polymorphism:
● Static (Compile-time) Polymorphism: Method overloading makes it possible
for several methods to have the same name but distinct parameters, which
supports static polymorphism. The number, type, and ordering of the parameters
supplied decide the proper method to be invoked at build time. This mechanism
enables the resolution of method calls based on the specific method signature.
● Dynamic (Runtime) Polymorphism: By allowing a subclass to provide a
distinct implementation of a method that is already specified in its superclass,
method overriding facilitates dynamic polymorphism. Runtime selection of the
appropriate method to be executed is based on the actual type of the object.
This is accomplished by utilizing a method signature with the same name,
return type, and parameters in both the superclass and the subclass. Through
a single interface, objects of various kinds can be treated equally thanks to the
runtime polymorphic behavior.

Example demonstrating function overriding in Java:


class Animal {
public void makeSound() {
[Link](“The animal makes a sound.”);
}
}
class Cat extends Animal {
@Override
public void makeSound() {

07
NOTES [Link](“Meow!”);
}
}
class Dog extends Animal {
@Override
public void makeSound() {
[Link](“Woof!”);
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
[Link](); // Output: “The animal makes a sound.”
Cat cat = new Cat();
[Link](); // Output: “Meow!”
Dog dog = new Dog();
[Link](); // Output: “Woof!”
}
}

The ‘Animal’ class in the example above defines a function called’makeSound()’. Both
the ‘Cat’ and ‘Dog’ classes offer their own implementations of the’makeSound()’
method and derive from the ‘Animal’ class. When the ‘makeSound()’ method is
invoked on objects of the ‘Cat’ and ‘Dog’ classes, their individual implementations
are executed, resulting in distinct outputs.

Annotating a method in a subclass to indicate that it should take the place of a


method in its superclass is done using the ‘@Override’ annotation. If the comparable
method in the superclass has a different method signature than the subclass’s, it
aids in the detection of potential problems during compilation.

Dynamic method dispatch is a mechanism that handles the calling of a method


that has been overridden at runtime rather than at compile time. The Java Virtual
Machine (JVM) determines the exact type of the object being referenced when
a method is called via a reference variable, and then it executes the matching
method implementation from the subclass.

Function overriding is the act of redefining a method in a subclass, while dynamic


method dispatch is the runtime mechanism that determines which overridden
method implementation to execute based on the actual object type. Function
overriding is a concept, and dynamic method dispatch is the underlying mechanism
that enables polymorphism in object-oriented programming.

Overriding methods with throws clause


The method name and its parameters are contained in the method signature, must
be the same in the subclass when a method is overridden. However, compared
to the exceptions thrown by the superclass method, the subclass’s overridden
method may throw the same, more specific, or unchecked exceptions. A more
significant or brand-new checked exception not mentioned in the throws clause of
the superclass function may not be thrown.
08
The overriding method in the subclass has the option to throw unchecked exceptions
or no exceptions if the superclass method’s throws clause does not declare any
NOTES
checked exceptions. Additionally, the overriding function may decide to throw more
specific checked exceptions, but it is not mandatory.

Consider the following example:

class Superclass {
public void doSomething() throws IOException {
// ...
}
}
class Subclass extends Superclass {
@Override
public void doSomething() throws FileNotFoundException {
// ...
}
}

In this example, the ‘Superclass’ has a method ‘doSomething()’ that declares


‘throws IOException’. The Subclass overrides this method and specifies ‘throws
FileNotFoundException’, which is a narrower exception compared to ‘IOException’.

CHECK YOUR PROGRESS


8. Polymorphism enables the creation of ___________ code that can work
with objects of different classes, enhancing reusability and reducing code
duplication.
9. The ___________ keyword is used to annotate a method in a subclass that is
intended to override a method in its superclass.
10. When a method is overridden in the subclass, the superclass implementation
of the method is completely replaced. [True/False]
11. Dynamic method dispatch is determined at compile-time based on the
reference type of the variable. [True/False]

4.5
Abstract and Final Keywords

Abstract class
The ‘abstract’ keyword in Java designates an abstract class. It can contain both
non-abstract methods (with a body) and abstract methods (methods without a
body). Abstraction allows us to focus on the functionality of an object rather than
its implementation details.
09
NOTES To be used, an abstract class needs to be extended and its abstract methods need
to be implemented in the subclass. The objects of an abstract class cannot be
made by hand.

abstract class Animal {


private String name;
public Animal(String name) {
[Link] = name;
}
public abstract void makeSound();
public void sleep() {
[Link](“The animal is sleeping.”);
}
public String getName() {
return name;
}
}
class Dog extends Animal {
public Dog(String name) {
super(name);
}
public void makeSound() {
[Link](“The dog barks.”);
}
}
class Cat extends Animal {
public Cat(String name) {
super(name);
}
public void makeSound() {
[Link](“The cat meows.”);
}
}
public class Main {
public static void main(String[] args) {
Animal dog = new Dog(“Buddy”);
Animal cat = new Cat(“Whiskers”);
[Link](); // Output: The dog barks.
[Link](); // Output: The cat meows.
[Link](); // Output: The animal is sleeping.
[Link](); // Output: The animal is sleeping.
[Link]([Link]()); // Output: Buddy
[Link]([Link]()); // Output: Whiskers
}
}

This example uses the ‘Animal’ class, which is specified as an abstract class and
has the methods’makeSound()’ and’sleep()’ that are both abstract. ‘getName()’ is

10
a getter method and a private instance variable for the name in the Animal class.
The ‘Dog’ and ‘Cat’ classes give their own implementations of the’makeSound()’
NOTES
method and extend the ‘Animal’ class. In the Main class, we create objects of type
‘Dog’ and ‘Cat’ and call their respective ‘makeSound()’ and ‘sleep()’ methods. We
also retrieve the names of the animals using the ‘getName()’ method.

Final Class
Java uses the ‘final’ keyword to enforce limitations. It prohibits a class from being
extended or subclassed when applied to the class. You can mark a class as final
by putting the “final” keyword before the class declaration. Final classes are
commonly employed when there is a need to prohibit any further modifications or
extensions to a class.

Example 1: Simple final class

final class Circle {


private double radius;
public Circle(double radius) {
[Link] = radius;
}
public double getArea() {
return [Link] * radius * radius;
}
}
// Uncomment the code below to see an error when trying to ex-
tend the final class.
// class SubCircle extends Circle {} // Error: Cannot inherit
from final ‘Circle’

Here, we have a straightforward Circle class that is designated as final. It has


a radius attribute and the getArea() function to determine the circle’s area. A
compilation error will occur if you attempt to construct a subclass of the Circle
class (such as SubCircle), as the Circle class is declared final.

Example 2: final class with final methods

final class MathUtils {


public static final double PI = 3.14159265359;
public static int add (int a, int b) {
return a + b;
}
public static int subtract (int a, int b) {
return a - b;
}
}
// Uncomment the code below to see an error when trying to
override a final method.
// class ExtendedMathUtils extends MathUtils{ // Error: Cannot
inherit from final ‘MathUtils’
// @Override
11
NOTES //
//
public static int add (int a, int b) {
return a + b + 10;
// }
// }

In this example, we have a MathUtils class marked as final, and it contains some
static utility methods for basic math operations. The PI constant is also marked
as final, meaning its value cannot be changed. If you try to create a subclass (like
ExtendedMathUtils) of the MathUtilsclass or override any of its methods, it will
result in a compilation error because the methods in MathUtils are marked as final.

CHECK YOUR PROGRESS


12. Subclasses that extend an abstract class must provide an implementation
for all the _________ methods inherited from the abstract class.
13. Abstract classes are used when you want to provide a common structure for
a group of related classes. [True/False]
14. Final classes are often used when you want to prevent any further _________
to a class.

Activity
Research and analyse real-life examples where abstract classes could be useful.
Share your findings with the class and discuss the benefits and limitations of
using abstract classes in software development.

4.6
Interfaces

An interface is a Java programming structure


specifying a group of methods a class has to STUDY NOTE
implement. It acts as a contract, describing Interfaces may have default
the actions that any class that implements methods, which offer a
the interface must take, including the default implementation, as
procedures and, rarely, constants. Interfaces of Java 8. Interfaces can
make it possible for classes to implement develop by adding additional
numerous interfaces make implementing methods using default
multiple inheritance in Java easier. Only methods without collapsing
abstract methods and variables—no method the existing implementation
bodies—are permitted in an interface. An of classes that implement
interface cannot instantly instantiate, just like the interface.
an abstract class cannot.
12
We use the “interface” by a keyword and the name of the interface Full
abstraction is provided by interfaces since every method stated in an interface
NOTES
is declared but not implemented. An interface’s public, static, and final fields
exist.A class must offer implementations for each of the methods listed in
an interface when it does so. A class can implement numerous interfaces in
Java. by separating them with commas, enabling the attainment of multiple
inheritance of behaviour.

interface NewPrint{
void print();
}
class Test implements NewPrint{
public void print(){[Link](“Hello”);}
public static void main(String args[]){
Test obj = new Test();
[Link]();
}
}

The program outputs:

Hello

Comparison of Interface and Class

● Objects can be created from a class, making it instantiable, whereas an interface


cannot be instantiated directly.
● An interface cannot inherit from a class, but a class can inherit from another
class.
● Constructors can exist within a class, but interfaces do not have constructors.
● Class variables can be static, final, or neither, while variables within an interface
is static and definitive at all times. While a class can implement an interface, an
interface cannot implement a class.

Fig 2: Relationship between classes and interfaces

13
NOTES CHECK YOUR PROGRESS
15. All methods declared in an interface are implicitly _________ and _________.
16. An interface can be instantiated directly using the new keyword. [True/False]
17. A class can implement an interface and extend another class at the same
time.[True/False]
18. You are working on a project where you need to implement different types of
vehicles, such as cars, motorcycles, and bicycles. Each vehicle has common
attributes like the number of wheels, colour, and model, but they also have
specific behaviours. How would you utilize interfaces and classes to design
a flexible and extensible vehicle system?

Activity
List the characteristics and use cases of abstract classes and interfaces. After
completing the list, present your findings to the class, highlighting the similarities
and differences between the two concepts. Facilitate a class discussion to clarify
any doubts and reinforce the understanding of when to use abstract classes and
interfaces in Java programming.

4.7
Access Modifiers

Access modifiers are Java keywords that specify a program’s classes, methods,
variables, and constructors’ visibility or accessibility. They control which parts of a
program can access and interact with certain elements. There are four main access
modifiers in Java:

Public: The most accessibility is permitted by the public access modification.


It means that the class, method, variable, or constructor can be accessed from
anywhere, including from other classes, packages, or even different projects.

public class MyClass {


public String publicField;
public void publicMethod() {
[Link](“This is a public method.”);
}
}
public class Main {
public static void main(String[] args) {
14
MyClassobj = new MyClass();
// Accessing publicField directly
NOTES
[Link] = “Hello, world!”;
[Link]([Link]);
// Calling publicMethod
[Link]();
}
}

In this illustration, the class ‘MyClass’ has a public field called ‘publicField’ as well
as a public method called ‘publicMethod()’. ‘MyClass’ is created as an instance in
the Main class, and we use it to access the public field by giving it a value, then
printing that value. The public method is also used, which just prints a message
to the console. The ‘public’ access modifier allows the field ‘publicField’ and the
method ‘publicMethod()’ to be accessed from anywhere in the program, including
other classes and even different packages.

Protected: The protected access modifier permits access by subclasses, even if


they are in a separate package, as well as within the same package. It is commonly
used to provide accessibility to derived classes while still restricting access to
other classes.

public class Vehicle {


protected String brand;
protected void startEngine() {
[Link](“Engine started.”);
}
}
public class Car extends Vehicle {
private String model;
public Car(String brand, String model) {
[Link] = brand; // Accessing protected field from the super-
class
[Link] = model;
}
public void drive() {
[Link](“Driving the “ + brand + “ “ + model);
startEngine(); // Accessing protected method from the super-
class
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car(“Toyota”, “Camry”);
[Link]();
}
}

15
NOTES The ‘protected’ access modifier allows the field ‘brand’ and the method
‘startEngine()’ to be accessed within the class itself, as well as by any subclasses
that extend the ‘Vehicle’ class, such as the ‘Car’ class in this example.

Default (No Modifier): The default access level is used if no access modifier
is [Link] allows access within the same package but restricts access from
classes in different packages.

class Animal {
String name;
void eat() {
[Link](“The animal is eating.”);
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
[Link] = “Lion”; // Accessing default field within
the same package
[Link](); // Accessing default method within the same pack-
age
}
}

The function “eat()” and the field “name” can both be accessed within of a package
with the “default” access modifier, but not outside of it.

Private: The private access modifier provides the most restricted access. It limits
access to only within the same class. It is commonly used to encapsulate internal
implementation details and to hide them from other classes.

public class Emp {


private String name1;
private void displayInfo() {
[Link](“Employee Name: “ + name1);
}
public void setName(String name1) {
this.name1 = name1;
}
public void showInfo() {
displayInfo(); // Accessing private method within the same
class
}
}
public class Main {
public static void main(String[] args) {
Employee emp = new Employee();
[Link](“John Doe”); // Accessing private field via public
setter method

16
[Link](); // Accessing private method via public method
}
NOTES
}

The private access modifier restricts the visibility of the ‘name1’ field and the
‘displayInfo()’ method to within the same class only. They are inaccessible from
within the class as well as from subclasses.
Modifier Class Package Subclass
public Accessible Accessible Accessible

protected Accessible Accessible Accessible

default Accessible Accessible Not- Accessible

private Accessible Not- Accessible Not- Accessible

CHECK YOUR PROGRESS


19. The default access modifier (also known as package-private) provides access
within the ________________.
20. Access modifiers can be changed at runtime based on specific conditions.
[True/False]
21. You are developing a banking application that consists of multiple classes
representing different account types. The BankAccount class contains a
private field balance that stores the account balance. You want to allow access
to the balance field only through a public method named getBalance(). To
achieve this, you would declare the balance field with the ________________
access modifier and the getBalance() method with the ________________
access modifier.

4.8
Method Overriding with
Access Modifiers

As mentioned previously, A subclass can implement a variant version of a method


that is already defined in its superclass by using method overriding. Now, let’s
explore method overriding in the context of access modifiers. The overridden
method’s access modifier in the subclass cannot be more restrictive than that in
the superclass. This is a rigorous requirement that must be adhered to.

Let us see the examples based on access modifiers in the decreasing order of
restriction.
17
NOTES Private
Private method overriding is not possible in Java. Private methods in a superclass
are not accessible to subclasses, so they cannot be overridden.

class Superclass {
private void display() {
[Link](“Superclass display”);
}
public void callDisplay() {
display();
}
}
class Subclass extends Superclass {
private void display() {
[Link](“Subclass display”);
}
}
public class Main {
public static void main(String[] args) {
Subclass obj = new Subclass();
[Link](); // Output: Superclass display
}
}

Because the private method in the “Subclass” does not supersede the method
in the “Superclass,” when we call the “callDisplay()” method on an object of the
“Subclass,” it calls the “display()” method in the “Superclass.”Consequently, in
Java, private methods cannot be overridden.

Default
Unlike private methods, default methods can be overridden in implementing
classes.

interface MyInterface {
default void display() {
[Link](“Default display method in MyInterface”);
}
}
class MyClass implements MyInterface {
@Override
public void display() {
[Link](“Overridden display method in MyClass”);
}
}
public class Main {
public static void main(String[] args) {
MyClassobj = new MyClass();
[Link](); // Output: Overridden display method in MyClass
}
}
18
When we create an object of ‘MyClass’ and call the ‘display()’ method, the
overridden method in ‘MyClass’ is executed, which prints “Overridden display
NOTES
method in MyClass”.

Protected
Subclasses in Java have the ability to override protected methods. Subclasses may
have access to the method even if they are in a separate package thanks to the
protected access feature.

class Superclass {
protected void display() {
[Link](“Superclass display”);
}
}
class Subclass extends Superclass {
@Override
protected void display() {
[Link](“Subclass display”);
}
}
public class Main {
public static void main(String[] args) {
Subclass obj = new Subclass();
[Link](); // Output: Subclass display
}
}

The override function is called when we construct an object of type “Subclass” and
invoke the “display()” method in ‘Subclass’ is executed, which prints “Subclass
display”.

Public
In Java, public methods can be overridden in subclasses. Any class may access the
method without restriction thanks to the public access feature.

class Superclass {
public void display() {
[Link](“Superclass display”);
}
}
class Subclass extends Superclass {
@Override
public void display() {
[Link](“Subclass display”);
}
}
public class Main {
public static void main(String[] args) {
Subclass obj = new Subclass();
19
NOTES [Link]();
}
// Output: Subclass display

The override function is called when we construct an object of “Subclass” and call
the “display ()” method in ‘Subclass’ is executed, which prints “Subclass display”.

CHECK YOUR PROGRESS


You are working on a project that involves designing a system for managing
different types of vehicles. The project includes a superclass called Vehicle, and
several subclasses such as Car, Motorcycle, and Truck that extend the Vehicle
class. Each subclass needs to override a method called startEngine(), which
starts the engine of the corresponding vehicle.

Fill in the blanks:


class Vehicle {
public void startEngine() {
[Link](“Starting the engine of the vehicle.”);
}
}
class Car extends Vehicle {
____Blank #22_____ void startEngine() {
[Link](“Starting the engine of the car.”);
}
}
class Motorcycle extends Vehicle {
public ___Blank #23____startEngine() {
[Link](“Starting the engine of the motorcycle.”);
}
}
class Truck extends Vehicle {
public void __Blank #24__() {
[Link](“Starting the engine of the truck.”);
}
}
public class Main {
public static void main(String[] args) {
Vehicle car = new Car();
Vehicle motorcycle = new Motorcycle();
Vehicle truck = new Truck();
[Link]();
[Link]();
[Link]();
}
}

20
4.9 NOTES
Summary

● In Java, a class can borrow traits and behaviors from another class thanks to a
mechanism known as inheritance.
● Inheritance in Java can take the form of numerous inheritance differs from
single inheritance, in which a class derives from numerous superclasses, is not
supported.
● The capacity of an object to display several forms or behaviours depending on
its real object type is known as [Link] overloading and method
overriding can be used to achieve it.
● By overriding a method, a subclass can implement a method that is already
defined in its superclass.
● In Java, declaring method overloading is the practice of having multiple methods
within a class with the same name but different argument lists.
● In Java, an interface is a group of abstract methods that establishes a contract
for classes that implement it. By default, an interface’s public, static, and final
fields are all final and abstract methods.
● A class in Java has the capability to implement multiple interfaces, enabling it
to inherit behaviour from multiple sources.
● Access modifiers in Java determine the class, method, and field visibility and
accessibility. Public, protected, default (package-private), and private are some
examples of these modifiers.
● Public: Accessible from any class or package.
● Protected: Accessible even if they are in a different package, within the same
package or its subclasses.
● Default (Package-private): only available inside the same box.
● Private: Accessible only within the same class.

4.10
Case Study

Tata Motors and Vehicle Hierarchy


Inheritance and polymorphism play a crucial role in the design and development of
software systems for automotive companies. Tata Motors, one of India’s leading
automobile manufacturers, utilizes these concepts to create an efficient and flexible
vehicle hierarchy.
21
NOTES Tata Motors uses inheritance to establish a hierarchical structure for their vehicle
models. The base class, “Vehicle,” encapsulates common attributes and behaviours
shared by all vehicles, such as engine capacity, seating capacity, and fuel efficiency.
Derived classes, such as “Sedan,” “SUV,” and “Hatchback,” inherit from the “Vehicle”
class, inheriting its properties while adding specific characteristics unique to each
vehicle type.

Polymorphism is essential in Tata Motors’ software system to handle various types


of vehicles within the hierarchy. Polymorphic behaviour allows the company to
treat different vehicle objects uniformly, simplifying processes such as inventory
management, production planning, and maintenance. For instance, regardless of
the specific vehicle type, a common interface or method can be used to perform
operations like starting the engine, calculating mileage, or checking service
requirements.

Benefits and Impact:


1. Code Reusability: Inheritance enables Tata Motors to reuse code from the base
class across multiple derived classes, minimizing redundancy and improving
development efficiency.
2. Flexibility and Extensibility: The hierarchical structure allows Tata Motors
to easily introduce new vehicle types or modify existing ones by leveraging
inheritance and polymorphism, reducing development time and cost.
3. Maintenance and Updates: The derived classes immediately inherit changes
made to the base class, ensuring consistent updates and reducing the effort
required for maintenance.
4. Improved System Integration: Polymorphic behaviour allows different vehicle
types to be seamlessly integrated into various software systems, such as
manufacturing processes, customer management, and sales.

By effectively implementing inheritance and polymorphism in their software


systems, Tata Motors optimizes code organization, enhances software modularity,
and improves overall efficiency in vehicle design, development, and management.

Questions:
1. How does the use of inheritance in Tata Motors’ vehicle hierarchy contribute to
code reusability and development efficiency? Provide specific examples of how
common attributes and behaviours are inherited and reused across different
vehicle types.
2. Discuss the advantages of using polymorphism in Tata Motors’ software system.
How does polymorphism simplify processes such as inventory management,
production planning, and maintenance? Provide real-life scenarios where
polymorphic behaviour allows for seamless integration of different vehicle
types into various software systems.

22
4.11 NOTES
Terminal Questions

SHORT ANSWER QUESTIONS


1. Is the below code written correctly? Explain the functionality of the code and
give the output.
package pk1;
class A
{
protected static String str = “Hello”;
}
class B extends A
{
}
class C extends B
{
static void methodOfC()
{
[Link](str);
}
}
public class MainClass
{
public static void main(String[] args)
{
[Link]();
}
}
2. Trace the error in the following code snippet and rewrite the correct code:
class A

{
public void methodOfA()
{
[Link](“Class A”);
}
}
class B extends A
{
@Override
void methodOfA()
{
[Link](“Class B”);
}
}
23
NOTES 3. Inheritance promotes code reusability. Discuss how inheritance achieves this
and provide an example.

LONG ANSWER QUESTIONS


1. You are designing a software system for a school that manages different types
of employees, including teachers and administrators. Each employee has
unique attributes and behaviours. Implement the employee hierarchy using
inheritance in Java.
2. You are developing a banking application that involves different types of
accounts, including savings accounts and checking accounts. Each account has
a specific interest rate and balance calculation logic. Implement the account
types using function overriding in Java.

MULTIPLE CHOICE QUESTIONS


1. Which of the following statements about inheritance in Java is correct?
a) Java supports multiple inheritance.
b) Inheritance allows a class to inherit multiple superclasses.
c) Private members of the superclass are accessible in the subclass.
d) The “final” keyword can be used to prevent a class from being inherited.
2. Highlight the difference between “extends” and “implements” keywords in Java:
a) “Extends” is used to implement inheritance, while “implements” is used
to implement interfaces.
b) “Extends” is used to implement interfaces, while “implements” is used to
implement inheritance.
c) “Extends” is used to extend the functionality of a class, while “implements”
is used to extend the functionality of an interface.
d) “Extends” is used to implement polymorphism, while “implements” is
used to implement encapsulation.
3. Which of the following statements correctly describes method overriding in
Java?
a) Overriding allows a subclass to provide a different implementation of a
method defined in its superclass.
b) Overriding is only applicable to static methods.
c) Overriding can only be done within the same package.
d) Overriding does not require the use of the “override” keyword.
4. Which of the following is the output of the below code snippet?
class A {
public void display() {
[Link](“Class A”);
}
}
class B extends A {
public void display() {

24
[Link](“Class B”);
}
NOTES
}
public class Main {
public static void main(String[] args) {
A obj = new B();
[Link]();
}
}
a) Class A
b) Class B
c) Compiler error
d) Runtime error
5. Which of the following examples demonstrates the correct usage of the “is-a”
relationship in Java?
a) A Car class extending a Vehicle class.
b) A Vehicle class containing a Car object.
c) A Person class implementing a Student interface.
d) A Student class having a reference to a Teacher object.
6. Which of the following best describes runtime polymorphism in Java?
a) The determination of method implementation occurs during the compilation
phase.
b) The determination of method implementation occurs during the runtime.
c) The selection of method implementation is based on the data type of the
object.
d) The determination of method implementation is influenced by the class
hierarchy.
7. What is the output of the below code?
class Shape {
public void draw() {
[Link](“Drawing a shape”);
}
}
class Circle extends Shape {
public void draw() {
[Link](“Drawing a circle”);
}
}
class Square extends Shape {
public void draw() {
[Link](“Drawing a square”);
}
}

25
NOTES public class Main {
public static void main(String[] args) {
Shape shape1 = new Circle();
Shape shape2 = new Square();
[Link]();
[Link]();
}
}
a) Drawing a shape, Drawing a shape
b) Drawing a circle, Drawing a square
c) Drawing a circle, Drawing a shape
d) Drawing a shape, Drawing a square
8. What is the output of the below code?
class Animal {
public void makeSound() {
[Link](“Animal makes a sound”);
}
}
class Cat extends Animal {
public void makeSound() {
[Link](“Cat meows”);
}
}
class Dog extends Animal {
public void makeSound() {
[Link](“Dog barks”);
}
}
public class Main {
public static void main(String[] args) {
Animal animal1 = new Animal();
Animal animal2 = new Cat();
Animal animal3 = new Dog();
[Link]();
[Link]();
[Link]();
}
}
a) Animal makes a sound, Animal makes a sound, Animal makes a sound
b) Animal makes a sound, Cat meows, Dog barks
c) Animal makes a sound, Animal makes a sound, Dog barks
d) Animal makes a sound, Cat meows, Animal makes a sound

26
9. Find the error in the below code:
private class A
NOTES
{
private class B
{
private class C
{
}
}
}
a) Class A can’t be private
b) Class B can’t be private
c) Class C can’t be private
d) Class C should have some content in the body
10. Which of the following statements about abstract classes and interfaces in
Java is correct?
a) Abstract classes have the capability to offer incomplete implementation of
methods, unlike interfaces.
b) Abstract classes are allowed to possess constructors, unlike interfaces.
c) 
Abstract classes enable the attainment of multiple inheritance, while
interfaces do not.
d) Abstract classes and interfaces are distinct concepts in Java that do not
overlap.
11. What is the purpose of declaring a class as final in Java?
a) To prevent other classes from accessing its methods.
b) To make the class immutable.
c) To indicate that the class is the final version and cannot be modified.
d) To enhance the efficiency of the class.
12. What will be the output of this code?
interface MyInterface {
void myMethod();
}
class MyClass implements MyInterface {
public void myMethod() {
[Link](“Hello”);
}
}
public class Main {
public static void main(String[] args) {
MyInterfaceobj = new MyClass();
[Link]();
}
}

27
NOTES a) Hello
b) Compilation Error: MyClass should implement MyInterface
c) Compilation Error: Cannot instantiate MyInterface
d) Runtime Error: NoSuchMethodError
13. What will be the output of the following code?
final class MyFinalClass {
void display() {
[Link](“Final Class”);
}
}
class SubClass extends MyFinalClass {
void display() {
[Link](“SubClass”);
}
}
public class Main {
public static void main(String[] args) {
MyFinalClassobj = new SubClass();
[Link]();
}
}
a) Final Class
b) SubClass
c) Compilation Error: Cannot extend final class
d) Runtime Error: NoSuchMethodError
14. What is the output of the following code?
class A {
protected void display() {
[Link](“Class A”);
}
}
class B extends A {
public void display() {
[Link](“Class B”);
}
}
public class Main {
public static void main(String[] args) {
A obj = new B();
[Link]();
}
}

28
a) Class A
NOTES
b) Class B
c) Compilation Error: display() in B cannot override display() in A
d) Compilation Error: incompatible types
15. Which of the following statements is true?
a) Overriding can only be achieved when there is a has-a relationship
b) Data members can be used in Polymorphism
c) In case of overloading, it’s the responsibility of the compiler to bind the
method calls with the method body based on method signatures.
d) Constructor overloading is dynamic Polymorphism

4.12
Answers

CHECK YOUR PROGRESS


1. Super 13. structure
2. Extends 14. modifications
3. Dog 15. public, abstract
4. To be solved by student 16. False
5. True 17. True
6. False 18. To be solved by student
7. Object 19. same package
8. generic 20. False
9. @Override 21. private, public
10. True 22. public
11. False 23. void
12. Abstract 24. startEngine

SHORT ANSWER QUESTIONS


1. No, the code is not written correctly. There is an error in the [Link] error is
in the methodOfC() in class C. Since str is a static variable, it can be accessed
directly using the class name A instead of using an instance or subclass.
Therefore, the correct code should be [Link] instead of just str.

// No package declaration is needed for simplicity


class A {
protected static String str = “Hello”;
}
29
NOTES class B extends A {
// No additional code needed
}
class C extends B {
static void methodOfC() {
[Link]([Link]); // Access the static variable
‘str’ from class ‘A’
}
}
public class MainClass {
public static void main(String[] args) {
[Link](); // Invoke the ‘methodOfC’ in class ‘C’
}
}
class A {
public void methodOfA() {
[Link](“Class A”);
}
}
class B extends A {
@Override
public void methodOfA() {
[Link](“Class B”);
}
}
2. A key idea in object-oriented programming is inheritance, which encourages
code reuse by enabling new classes (subclasses or derived classes) to take
on the traits (fields and methods) of existing classes (superclasses or base
classes). This makes it possible for developers to construct a new class that
has properties shared with an existing class while also allowing customization
and extension.

class Animal {
String name;
Animal(String name) {
[Link] = name;
}
void speak() {
[Link](“Animal sound”);
}
}
class Dog extends Animal {
Dog(String name) {
super(name);
}
void speak() {
[Link](“Woof!”);
}
30
}
class Cat extends Animal {
NOTES
Cat(String name) {
super(name);
}
void speak() {
[Link](“Meow!”);
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog(“Buddy”);
Cat cat = new Cat(“Whiskers”);
[Link](); // Output: Woof!
[Link](); // Output: Meow!
}
}

The Animal class is the superclass in this illustration, and both Dog and Cat are
subclasses that inherit from Animal. By utilizing inheritance, common attributes and
methods such as the name field and speak() method are shared among subclasses,
while each subclass can override and provide their specific implementation.

LONG ANSWER QUESTIONS


1. To implement the employee hierarchy using inheritance, you can define a base
class Employee and create derived classes Teacher and Administrator that
inherit from the base class.

class Employee {
protected String name;
protected int age;
public Employee(String name, int age) {
[Link] = name;
[Link] = age;
}
public void displayInfo() {
[Link](“Name: “ + name);
[Link](“Age: “ + age);
}
}
class Teacher extends Employee {
private String subject;
public Teacher(String name, int age, String subject) {
super(name, age);
[Link] = subject;
}
@Override
public void displayInfo() {

31
NOTES [Link]();
[Link](“Subject: “ + subject);
}
}
class Administrator extends Employee {
private String department;
public Administrator(String name, int age, String de-
partment) {
super(name, age);
[Link] = department;
}
@Override
public void displayInfo() {
[Link]();
[Link](“Department: “ + department);
}
}
public class Main {
public static void main(String[] args) {
Teacher teacher = new Teacher(“John Doe”, 35,
“Math”);
[Link]();
Administrator administrator = new Administrator(“-
Jane Smith”, 40, “Finance”);
[Link]();
}
}
2. class Account {

protected double balance;


public Account(double balance) {
[Link] = balance;
}
public void calculateInterest() {
[Link](“Interest calculation logic for a ge-
neric account.”);
}
public void displayBalance() {
[Link](“Account balance: $” + balance);
}
}
class SavingsAccount extends Account {
private double interestRate;
public SavingsAccount(double balance, double intere-
stRate) {
super(balance);
[Link] = interestRate;
}
32
@Override
public void calculateInterest() {
NOTES
double interest = balance * interestRate / 100;
[Link](“Interest calculated for Savings Ac-
count: $” + interest);
}
}
class CheckingAccount extends Account {
private double transactionFee;
public CheckingAccount(double balance, double transac-
tionFee) {
super(balance);
[Link] = transactionFee;
}
@Override
public void displayBalance() {
double balanceAfterFee = balance - transactionFee;
[Link](“Account balance after fee deduction:
$” + balanceAfterFee);
}
}
public class Main {
public static void main(String[] args) {
SavingsAccountsavingsAccount = new SavingsAccount(1000,
2.5);
[Link]();
CheckingAccountcheckingAccount = new CheckingAccount(500,
5);
[Link]();
}
}

MCQS
1. d) The “final” keyword can be used to prevent a class from being inherited.
2. a) “Extends” is used to implement inheritance, while “implements” is used
to implement interfaces.
3. a) Overriding enables a subclass to present an alternative implementation of
a method that is originally defined in its superclass.
4. b) Class B
5. a) A Car class extending a Vehicle class.
6. b) The selection of method implementation is determined at runtime.
7. b) Drawing a circle, Drawing a square
8. b) Animal makes a sound, Cat meows, Dog barks
9. a) Class A can’t be private
10. a) 
Abstract classes can provide partial implementation of methods, while
interfaces cannot.
33
NOTES 11. c) To indicate that the class is the final version and cannot be modified.
12. a) Hello
13. a) Final Class
14. b) Class B
15. c) In case of overloading, it’s the responsibility of the compiler to bind the
method calls with the method body based on method signatures.

4.13
Assignment
MULTIPLE CHOICE QUESTIONS
1. Find the output:
class A {
private void display() {
[Link](“Class A”);
}
}
class B extends A {
public void display() {
[Link](“Class B”);
}
}
public class Main {
public static void main(String[] args) {
A obj = new B();
[Link]();
}
}
a) Class A
b) Class B
c) Compilation Error: display() in B cannot override display() in A
d) Compilation Error: incompatible types
2. Find the output:
interface MyInterface {
default void myMethod() {
[Link](“Default Method”);
}
}

34
class MyClass implements MyInterface {
public void myMethod() {
NOTES
[Link](“Overridden Method”);
}
}
public class Main {
public static void main(String[] args) {
MyInterfaceobj = new MyClass();
[Link]();
}
}
a) Default Method
b) Overridden Method
c) Compilation Error: MyClass should implement MyInterface
d) Compilation Error: Cannot instantiate MyInterface
3. Find the output:
class A {
public void display() {
[Link](“Class A”);
}
}
class B extends A {
public void display() {
[Link](“Class B”);
}
}
class C extends A {
public void display() {
[Link](“Class C”);
}
}
public class Main {
public static void main(String[] args) {
A obj1 = new B();
A obj2 = new C();
[Link]();
[Link]();
}
}
What will be the output of the above code?
a) Class A, Class B
b) Class B, Class C
c) Class A, Class C
d) Compilation Error: incompatible types

35
NOTES 4. What is the output of the below code?
class A {
public void method() throws Exception {
[Link](“Class A”);
}
}
class B extends A {
public void method() throws RuntimeException {
[Link](“Class B”);
}
}
public class Main {
public static void main(String[] args) {
A obj = new B();
try {
[Link]();
} catch (Exception e) {
[Link](“Exception Caught”);
}
}
}
a) Class A
b) Class B
c) Exception Caught
d) Compilation Error: Exception in B not compatible with Exception in A
5. Find the output:
class Base {
public static void show() {
[Link](“Base::show() called”);
}
}
class Derived extends Base {
public static void show() {
[Link](“Derived::show() called”);
}
}
class Main {
public static void main(String[] args) {
Base b = new Derived();
[Link]();
}
}
a) Base::show() called b) Derived::show() called
c) Compiler Error d) Runtime Error

36
QUESTIONS
NOTES
1. You are building a banking application that needs to handle different types
of accounts, including Current Account, Savings Account, and Fixed Deposit
Account. Each account type has different functionalities such as depositing
money, withdrawing money, and calculating interest. Implement the account
types using interfaces in Java.
2. You are developing a game application that involves different types of characters,
including warriors, mages, and archers. Each character has different abilities
and behaviors. Implement the character types using abstract classes in Java.
3. You are developing a library management system that handles different types
of library items, including books and magazines. Each library item has unique
properties and behaviours. Implement the library item types using an abstract
class in Java.
4. You are developing a geometry application that involves different types of
shapes, including circles, rectangles, and triangles. Each shape has specific
properties and behaviours. Implement the shape types using final classes in
Java.
5. You are developing a music streaming application that supports various audio
formats, including MP3, WAV, and FLAC. Each audio format has specific
functionalities. Implement the audio formats using interfaces in Java.

4.14
References

Books:
● [Link]
en&gbpv=1&dq=Inheritance+in+Java&printsec=frontcover
● [Link]
EACAAJ?hl=en
● [Link]
NTuIDwAAQBAJ?hl=en&gbpv=1&dq=interfaces+in+java&printsec=
frontcover

Web References:
● [Link]
polymorphism-java/v
● [Link]
● [Link]

37

You might also like