PSOOP-Lecture 07-2024-25
PSOOP-Lecture 07-2024-25
• Abstraction
• Abstract class
2
Abstraction in Java
• Abstraction in Java is the process in which
we only show essential details/functionality to
the user.
• The non-essential implementation details are
not displayed to the user.
• Real world examples:
• Television remote control, Car
• Abstraction can be achieved with either
abstract classes or interfaces.
The Monopoly Property Example
• There are properties on a
monopoly board
• Railroads, Utilities, and Streets are kinds
of properties
Property
5
The Property class
public class Property {
6
Potential Solutions
1. Just leave it for the sub classes.
Have each sub class define getRent()
2. Define getRent() in Property and simply
return -1.
Sub classes override the method with more
meaningful behavior.
7
Solution 1: Leave it to the Sub - Classes
// no getRent() in Property
// Railroad and Utility DO have getRent() methods
12
Making getRent Abstract
public class Property {
}
Methods that are declared abstract have no body,
an undefined behavior.
13
Problems with Abstract Methods
Given getRent() is now an abstract method
what is wrong with the following code?
15
Abstract Classes Rules
1. A class with one or more abstract methods must be
declared abstract.
- Syntax error if not done.
- Can still decide to make class abstract even if no abstract
methods.
2. Objects of an abstract class cannot be instantiated.
-- Can still declare variables of this type
3. A subclass must implement all inherited abstract
methods or be abstract itself.
16
Abstract Classes
public abstract class Property {
}
// Other methods not shown
18
Sub Classes of Abstract Classes
• Classes that extend an abstract class must
provide a working version of any and all
abstract methods from the parent class
• or they must be declared to be abstract as
well
• could still decide to keep a class abstract
regardless of status of abstract methods
19
Implementing getRent()
public class Railroad extends Property {
20
A Utility Class
21
Polymorphism in Action
// getRent() in Property is abstract
22
final and static methods in abstract
classes
• Concrete methods in abstract classes can include
'final' and 'static' methods.
• A final method in an abstract class cannot be
overridden by subclasses.
• - Ensures that the method's implementation remains
unchanged.
• - Useful for defining behavior that should be
consistent across subclasses.
• Example:
class Vehicle {
final void engineType() {
System.out.println('Petrol Engine');
}
}
final and static methods in abstract
classes
• Static methods in abstract classes belong to
the class, not instances.
• - Can be called without creating an object of
the class.
• - Cannot be overridden by subclasses.
• Example:
abstract class Vehicle {
static void displayType() {
System.out.println('Vehicle type');
}
}
Abstract Class Summary
• A class that is declared with abstract keyword