MCA Java Programming Unit 4 Inheritance and Polymorphism
MCA Java Programming Unit 4 Inheritance and Polymorphism
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.
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.
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
}
}
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.
“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
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
}
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
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.
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.
class Superclass {
public void doSomething() throws IOException {
// ...
}
}
class Subclass extends Superclass {
@Override
public void doSomething() throws FileNotFoundException {
// ...
}
}
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.
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.
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.
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
interface NewPrint{
void print();
}
class Test implements NewPrint{
public void print(){[Link](“Hello”);}
public static void main(String args[]){
Test obj = new Test();
[Link]();
}
}
Hello
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:
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.
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.
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
4.8
Method Overriding with
Access Modifiers
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”.
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
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
{
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.
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
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.
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 {
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