[go: up one dir, main page]

0% found this document useful (0 votes)
10 views25 pages

Lab 09 - OOP

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)
10 views25 pages

Lab 09 - OOP

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Object Oriented Programming Lab 09

Course: Object Oriented Programming (CL1004) Semester: Spring 2025


Instructor: Muhammad Nadeem Ghouri

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.

Abstract class in Java


In the world of Java programming, abstract classes play an important role in defining the structure of classes and
their behavior in the hierarchy. They provide a blueprint for other teams to follow, and some methods remain
undefined. This flexibility empowers developers to generate a well-organized and scalable codebase. In this section,
we will explore the concept of abstract classes in Java, examining their features, advantages, and best practices.

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.

Ways to achieve Abstraction


There are two ways to achieve abstraction in Java:

Using Abstract Class (0 to 100%)

Using Interface (100%)


Abstract Class in Java
An abstract class in Java acts as a partially implemented class that itself cannot be instantiated. It exists only for sub
classing purposes, and provides a template for its subcategories to follow. Abstract classes can have implementations
with abstract methods. Abstract methods are declared to have no body, leaving their implementation to subclasses.

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.

Abstract Method in Java


A method which is declared as abstract and does not have implementation is known as an abstract method.

Example of abstract method

Example of Abstract Class that has an Abstract Method


In this example, Bike is an abstract class that contains only one abstract method run. Its implementation is
provided by the Honda class.
Why use Abstract Classes?
Abstract classes are beneficial in various scenarios, including:

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.

Real Scenario of Abstract Class


In this example, Shape is the abstract class, and its implementation is provided by the Rectangle and Circle classes.
Mostly, we do not know about the implementation class (which is hidden to the end user), and an object of the
implementation class is provided by the factory method.
A factory method is a method that returns the instance of the class. We will learn about the factory method later.
In this example, if we create the instance of Rectangle class, draw() method of Rectangle class will be invoked.
Another Example of Abstract Class in Java

Abstract Class: Having Constructor, Data Member and Methods


An abstract class can have a data member, abstract method, method body (non-abstract method), constructor, and
even main() method.
Rule: If there is an abstract method in a class, that class must be abstract.

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.

Another Real Scenario of Abstract Class


The abstract class can also be used to provide some implementation of the interface. In such case, the end user may
not be forced to override all the methods of the interface.

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.

Best Practices for Using Abstract Classes


To make the most out of abstract classes in Java, consider the following best practices:

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.

 Java Interface also represents the IS-A relationship.


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

Why use a Java interface?


There are mainly three reasons to use an interface. They are given below.

 It is used to achieve abstraction.


 By interface, we can support the functionality of multiple inheritance.
 It is used to achieve loose coupling.

How to declare an interface?


An interface is declared by using the interface keyword. It provides total abstraction; it means all the methods in an
interface are declared with an empty body, and all the fields are public, static and final by default. A class that
implements an interface must implement all the methods declared in the interface.
Internal Addition by The Compiler
The Java compiler adds the public and abstract keywords before the interface method. Moreover, it adds public,
static and final keywords before data members.

In other words, Interface fields are public, static and final by default, and the methods are public and abstract.

Java 8 Interface Improvement


Since Java 8, interfaces can have default and static methods, which are discussed later.

Relationship Between Classes and Interfaces


As shown in the following figure, a class extends another class, an interface extends another interface, but a class
implements an interface.
Interface Example
In this example, the Printable interface has only one method, and its implementation is provided in the A6 class.

Interface Example: Drawable


In this example, the Drawable interface has only one method. The Rectangle and Circle classes provide their
implementation. In a real scenario, an interface is defined by someone else, but different implementation providers
provide its implementation. Moreover, it is used by someone else. The implementation part is hidden from the user
who uses the interface.
Java Interface Example: Bank
Let's see another example of a Java interface that provides the implementation of the Bank interface.

Multiple Inheritance in Java by Interface


If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple
inheritance.
Multiple inheritance is not supported through classes in Java, but it is possible through an
interface. Why?

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.

Interfaces and Polymorphism


One of the significant benefits of interfaces is their ability to support polymorphism. Since Java supports interface
reference variables, we can use an interface type to refer to any object of a class that implements the interface. It
enables flexibility and extensibility in your codebase.

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:

Java 8 Static Method in Interface


Since Java 8, we can have static methods in the interface. Let's see an example:
What is a marker or tagged interface?
An interface that has no members is known as a marker or tagged interface, for example, Serializable, Cloneable,
Remote, etc. They are used to provide some essential information to the JVM so that the JVM may perform some
useful operations.

Nested Interface in Java


Note: An interface can have another interface, which is known as a nested interface. We will learn it in detail in
the nested classes chapter. For 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

Definition A class that cannot be A contract specifying


instantiated and may methods that must be
contain abstract and implemented by a class.
concrete methods.

Usage It is used when we need It is used when we need to


shared functionality among enforce a common protocol
related classes. or contract across classes.

Declaration The abstract keyword is The interface keyword is


used to declare an abstract used to declare an interface.
class.

Keyword An abstract class can be An interface can be


extended using the implemented using the
keyword "extends". keyword "implements".

Methods Abstract class can have An interface can have only


abstract and non-abstract abstract methods. Since
methods. Java 8, it can have default
and static methods also.

Inheritance Abstract class does not Interface supports multiple


support multiple inheritance.
inheritance.

Constructors It can have constructors to It does not have


initialize objects. constructors because
interfaces cannot be
instantiated.

Fields and Variables Abstract class can have Interface has only static and
final, non-final, static and final variables.
non-static variables.

Implementation An abstract class can The interface cannot


provide the implementation provide the implementation
of the interface. of an abstract class.
Inheritance An abstract class can An interface can extend
extend another Java class another Java interface only.
and implement multiple
Java interfaces.

Members A Java abstract class can Members of a Java


have class members like interface are public by
private, protected, etc. default.

Example public abstract class Shape{ public interface Drawable{


public abstract void draw(); void draw();
} }

Important Points to Remember


 Interfaces provide abstraction: They define a contract without specifying implementation.
 Interfaces support multiple inheritance: A class can implement multiple interfaces.
 All fields in an interface are public, static, and final by default.
 All methods in an interface are public and abstract by default (except default, static, and private methods).
 Java 8 introduced default and static methods: Default methods provide implementation inside the interface,
while static methods belong to the interface itself.
 Java 9 introduced private methods in interfaces, which help in code reuse within the interface.
 A class implementing an interface must implement all its methods, unless it is an abstract class.
 Interfaces support polymorphism: An interface reference can hold objects of different implementing classes.
 Marker interfaces (for example, Serializable, Cloneable) do not have methods but provide metadata to the JVM.
 Interfaces can extend other interfaces: An interface can inherit from one or more interfaces.
Example- 01: PSL 2025 – Cricket Match Simulation using Interfaces
The Pakistan Super League (PSL) 2025 is launching a cricket simulation game to analyze player performance
using Object-Oriented Programming concepts. You are hired as a Java developer to build a prototype using
interfaces to simulate different types of cricket players and match scenarios. The goal is to ensure flexibility,
reusability, and multiple-role behaviors using interface-based design.
Tasks:
1. Create an interface Player with a method play().

2. Create two interfaces Batsman and Bowler that extend Player and add specific methods like battingStats()
and bowlingStats().

3. Implement these interfaces in classes AllRounder, PureBatsman, and PureBowler accordingly.

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:

1. Define an interface Product with a method displayDetails().

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 

You might also like