Lecture_10_Abstract Classes
Lecture_10_Abstract Classes
Classes in Java
Lecture
10
Agenda Points
Key Points:
1. The method must have the same name and parameters as the parent class.
2. The return type must be the same or a subtype (covariant return type).
3. The method in the subclass must be at least as accessible (or more) as the
Purpose:
To provide a base class with common functionality, while allowing
subclasses to provide specific implementations of abstract methods.
Rules for Abstract Classes
// Regular method
public void stop() {
System.out.println("Vehicle stopped");
}
}
class Car extends Vehicle {
@Override
public void start() {
System.out.println("Car started");
}
Practical Example of Abstract
Class
public class Main {
public static void main(String[] args) {
Vehicle myCar = new Car();
Method Overriding:
Abstract Classes:
You are designing a system for an animal shelter. The system needs to
manage different types of animals, and each animal type has a
different sound. The shelter wants to ensure that no one can instantiate
an animal directly, but each specific type of animal (e.g., Dog, Cat)
should have a custom sound.
Question:
1. Create an abstract class Animal with an abstract method
makeSound().
2. Implement two subclasses, Dog and Cat, that extend Animal and
override makeSound() to print "Dog barks" and "Cat meows",
respectively.
3. In the main method, instantiate both Dog and Cat, and call their
makeSound() methods.
Quiz Scenario 1: Animal Shelter
You are developing a vehicle system for a car rental service. The
service rents out cars and motorcycles. Each vehicle type should
have its own implementation of starting the engine, but all
vehicles should have a stop method that prints "Vehicle stopped".
Question:
1. Create an abstract class Vehicle with an abstract method
startEngine() and a concrete method stop().
2. Implement two subclasses, Car and Motorcycle, that override
the startEngine() method to print "Car engine started" and
"Motorcycle engine started", respectively.
3. In the main method, create objects for both Car and
Motorcycle, and call both startEngine() and stop() methods for
each.
Quiz Scenario 2: Vehicle System
// Abstract class Vehicle
abstract class Vehicle {
// Abstract method
public abstract void startEngine();
// Concrete method
public void stop() {
System.out.println("Vehicle stopped");
}
}