Java Exercise
In this exercise, you will create a Java program that demonstrates the use of **interfaces** and **abstract classes**. First, you will define an **interface** called Vehicle
that will have an abstract method called move()
. Next, you will create an **abstract class** called Car
that will implement some of the behavior for vehicles and will have an abstract method called details()
. Finally, you will create a concrete class called Car
that implements both the move()
and details()
methods, demonstrating how interfaces and abstract classes combine to create a strong and flexible structure in your program.
Instructions:
- Create an interface called
Vehicle
with the abstract method move()
.
- Create an abstract class called
Car
that implements the Vehicle
interface and declares an abstract method details()
.
- Create a concrete class called
Car
that implements the move()
and details()
methods.
- In the main method, create an object of type
Car
and call methods to demonstrate the use of Interfaces and Abstract Classes.
This exercise will help you understand how **interfaces** and **abstract classes** are used to define and organize common behaviors in Java applications, improving their structure and maintainability.
View Example Code
interface Vehicle {
void move(); // Abstract method to move the vehicle
}
abstract class Car implements Vehicle {
// Partially implemented method
public void move() {
System.out.println("The car is moving.");
}
// Abstract method
public abstract void details();
}
class SportsCar extends Car {
// Implementing the abstract method details
@Override
public void details() {
System.out.println("This is a sports car.");
}
}
public class Main {
public static void main(String[] args) {
// Create an object of type SportsCar
SportsCar sportsCar = new SportsCar();
// Call the methods
sportsCar.move(); // Output: "The car is moving."
sportsCar.details(); // Output: "This is a sports car."
}
}
Output:
The car is moving.
This is a sports car.
This program demonstrates how **interfaces** and **abstract classes** allow for more flexible and reusable designs. The Car
class implements the behavior defined in the Vehicle
interface and completes additional behavior in the abstract Automobile
class, resulting in a well-structured program.