Lab 09 - OOP
Lab 09 - OOP
Note:
• Maintain discipline during the lab.
• Listen and follow the instructions as they are given.
• Just raise hand if you have any problem.
• Completing all tasks of each lab is compulsory.
• Get your lab checked at the end of the session.
• Objective to understand Abstract class, Interface and Difference
between Abstract Class and Interface in Java.
A class that is declared with the abstract keyword is known as an abstract class in Java. It can have abstract and non-
abstract methods (method with the body).
Before learning the Java abstract class, let's understand the abstraction in Java first.
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS
where we type the text and send the message. We do not know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Points to Remember
An abstract class must be declared with an abstract keyword.
It can have abstract and non-abstract methods.
It cannot be instantiated.
It can have constructors and static methods also.
It can have final methods which will force the subclass not to change the body of the method.
Syntax of Abstract Classes
In Java, abstract classes are defined using the abstract keyword. Here's a basic syntax example:
In this example, Shape is an abstract class with one abstract method area() and one concrete method display().
Subclasses of Shape must implement the area() method, but they can inherit the display() method.
Code Reusability: Abstract classes facilitate code reuse by allowing common methods to be implemented once and
inherited by multiple subclasses.
Defining a Common Interface: Abstract classes can define a common interface for a group of related classes,
ensuring consistency in their structure and behavior.
Enforcing Method Implementation: Abstract classes can enforce the implementation of certain methods by
declaring them as abstract, thereby ensuring that subclasses provide necessary functionality.
Rule: If we are extending an abstract class that has an abstract method, we must either provide the implementation
of the method or make this class abstract.
Note: If we are beginner to Java, learn interface first then see this example.
Key Features of Abstract Classes
Abstract Methods: Abstract classes can have abstract methods, which are declared without a body. Subclasses
must provide concrete implementations for these methods.
Concrete Methods: Abstract classes can also contain concrete methods with defined behavior. Subclasses inherit
these methods along with their implementations.
Cannot be Instantiated: Abstract classes cannot be instantiated directly. They serve as a blueprint for other classes
and must be extended to be used.
Can Have Constructors: Abstract classes can have constructors, which are invoked when a subclass object is
created. These constructors are used to initialize the state of the abstract class.
Keep Abstract Classes Concise: Aim to keep abstract classes focused on a single responsibility to maintain clarity
and simplicity.
Use Abstract Classes for Related Objects: Abstract classes are best suited for scenarios where a group of related
objects share common characteristics and behaviors.
Prefer Interfaces for Multiple Inheritance: If a class needs to inherit from multiple sources, prefer using interfaces
over abstract classes, as Java doesn't support multiple inheritance for classes.
Provide Meaningful Abstract Methods: When defining abstract methods, ensure they have clear and meaningful
names that convey their purpose to subclasses.
Example - 01 - Developer Day 2025 – Programming Competition
You are participating in the Developer Day 2025 Programming Competition. One of the competition rounds
is titled "Master of Abstraction". Your task is to demonstrate your understanding of Abstract Classes in
Java through a coding challenge. The organizers have provided a real-world problem:
A programming task simulates a Game Arena where different types of players (e.g., Warrior, Mage, and
Archer) participate. All players have common properties like name, level, and health. They all must
implement a unique attack() method, but some share the same displayStats() behavior. You are required to
use abstract classes to model this behavior effectively.
Tasks:
1. Create an abstract class named Player with data members: name, level, and health. Include a
constructor to initialize these values.
2. Declare an abstract method attack() and a concrete method displayStats() in the Player class.
3. Create three subclasses: Warrior, Mage, and Archer, that extend Player and implement the attack()
method with class-specific messages.
4. In a Main class, instantiate at least two different player types and demonstrate polymorphism by calling
attack() and displayStats() using a Player reference.
5. Explain (in comments) why abstract classes are preferred in this scenario over interfaces.
Example - 02 - Systems Limited – Software House
You are hired as an intern Java developer at Systems Limited, a renowned software house. Your team is
working on a transport management system where different types of vehicles (e.g., Truck, Bus, and Car) are
handled through an abstract structure. The software should enforce each vehicle type to provide its own way
of calculating fuelEfficiency() while sharing some behaviors like displayInfo().
Tasks:
1. Design an abstract class Vehicle with data members registrationNumber, model, and capacity. Include a
parameterized constructor.
2. Define an abstract method fuelEfficiency() and a non-abstract method displayInfo() inside Vehicle.
3. Implement three subclasses: Truck, Bus, and Car that extend Vehicle and override fuelEfficiency() with
their own logic.
4. In a demo class, create a list or array of Vehicle references holding different subclass objects. Call
methods polymorphically.
5. Document in comments how abstract classes promote code reusability and scalability in large enterprise-
level applications like the one built at Systems Limited.
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 a method body. It is used to achieve abstraction and multiple inheritance in Java.
In other words, we can say that interfaces can have abstract methods and variables. It cannot have a method body.
In other words, Interface fields are public, static and final by default, and the methods are public and abstract.
As we have explained in the inheritance chapter, multiple inheritance is not supported in the case of a class because
of ambiguity. However, it is supported in the case of an interface because there is no ambiguity. Because the
implementation class provides its implementation. For example:
Inheritance of Interfaces
A class implements an interface, but one interface can extend another interface.
In this example, myAnimal is an interface reference variable of type Animal, referring to a Dog object. It
demonstrates polymorphic behavior, where the method calls are resolved at runtime based on the actual object type.
Java 8 Default Method in Interface
Since Java 8, we can have method body in interface. But we need to make it default method. Let's see an example:
Best Practices
Follow the Single Responsibility Principle (SRP): Design interfaces with a clear and single purpose. Each
interface should represent a cohesive set of behaviors.
Use Interfaces for Abstraction: Interfaces should focus on what needs to be done without concerning themselves
with how it's done. It promotes abstraction and decouples the implementation from the interface.
Prefer Composition over Inheritance: Interfaces are a key component of achieving composition over inheritance,
enabling flexible and modular designs.
Keep Interfaces Lean: Avoid bloating interfaces with unnecessary methods. Keep them concise and focused to
make them easier to understand and implement.
Differences Between Abstract Class and Interface
Abstract Class Interface
Fields and Variables Abstract class can have Interface has only static and
final, non-final, static and final variables.
non-static variables.
2. Create two interfaces Batsman and Bowler that extend Player and add specific methods like battingStats()
and bowlingStats().
4. Demonstrate polymorphism using the Player interface to hold different types of players and call common
methods.
6. Add a static method in the Player interface named tournamentInfo() that displays "PSL 2025 – Match
Day" and call it without creating any object.
Example 02: Daraz Shopping Mall – Product Interface Simulation
Daraz is launching a smart shopping module that allows different product categories (Electronics, Clothing,
Grocery) to interact using a flexible interface structure. You’ve been hired to design the solution using
interfaces and multiple inheritance in Java.
Tasks:
2. Define two interfaces Discountable and Deliverable with methods applyDiscount() and shippingInfo()
respectively.
3. Create a class Smartphone that implements all three interfaces and provides complete behavior.
4. Show how multiple inheritance is achieved using interfaces and invoke all three methods from the object
of Smartphone.
5. Use interface polymorphism to call the methods using Product, Discountable, and Deliverable reference
variables separately.
Thank you