Question
Try to make random collection of objects from the given code with random Properties and Behaviour, and in loop call some polymorphic method(s). Try to
Try to make random collection of objects from the given code with random Properties and Behaviour, and in loop call some polymorphic method(s).
Try to use abstractions and overloading.
public interface Movable {
void move();
}
To implement this interface in an abstract class,
public abstract class AbstractMovable implements Movable {
// This abstract class must implement the move() method
// because it is specified in the Movable interface
public abstract void move();
}
Here i create concrete classes that inherit from the abstract class and provide an implementation for the move() method:
public class Car extends AbstractMovable {
private String trademark;
public Car(String trademark) {
this.trademark = trademark;
}
@Override
public void move() {
System.out.println("Car is moving");
}
public void displayInfo() {
System.out.println("Trademark: " + trademark);
}
}
public class Lorry extends AbstractMovable {
private int carryingCapacity;
public Lorry(int carryingCapacity) {
this.carryingCapacity = carryingCapacity;
}
@Override
public void move() {
System.out.println("Lorry is moving");
}
public void load() {
System.out.println("Loading cargo");
}
public void displayInfo() {
System.out.println("Carrying capacity: " + carryingCapacity);
}
}
The Car and Lorry classes both inherit from the AbstractMovable class, which implements the Movable interface. They both provide an implementation for the move() method and have their own unique methods as well (displayInfo() and load(), respectively).
then create objects of these classes and call their methods like this:
Car car = new Car("Mustang");
car.move(); // prints "Car is moving"
car.displayInfo(); // prints "Trademark: Mustang"
Lorry lorry = new Lorry(500);
lorry.move(); // prints "Lorry is moving"
lorry.load(); // prints "Loading cargo"
lorry.displayInfo(); // prints "Carrying capacity: 900"
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started