LAB 6 Solution
LAB 6 Solution
Abstract classes in Java are mainly used as a prototype or a general template where all the methods
should be executed by subclasses, giving the program a basic structure. The Abstract classes contain
abstract methods that are implemented in subclasses and the methods with implementation done , this
allows to have a common structure while making compulsion for making some methods in subclasses.
By extending Vehicle, Car inherits its properties and methods while adding more specific features. This
shows that extending abstract class allows for more specific classification and reusability of code by
adding more specific features to subclasses like car class inherited all the data members and member
functions from Vehicle and has its own data members and member functions.
3) Defining an Interface
Interface Electric
interface Electric {
void chargeBattery();
void checkBatteryLevel();
}
Interfaces in Java define compulsory methods for classes that implement them. They have methods that
must be implemented by any class that implements the interface compulsorily. Interfaces cannot contain
any implementation like abstract classes or classes in general. This allows multiple inheritance because a
class can implement multiple interfaces, as they have no implementation done there will be no chance of
ambiguity like in “Deadly Diamond of Death”.
Class Tesla
This shows multiple inheritance in Java to some extent. The Tesla class inherits properties and methods
from the Car class which in turn extends Vehicle and implements the Electric interface. This allows Tesla
to inherit all the methods and data members from Car and Vehicle while also implementing the abstract
methods from Interface Electric which is multiple inheritance.
5) Demonstrating Functionality
The Vehicle class is a base for all vehicles with make, year, a drive() method to be implemented by
subclasses, and a displayDetails() method. The Car class extends Vehicle, adds a model, and extends
displayDetails(). The Electric interface has chargeBattery() and checkBatteryLevel() methods. The Tesla
class extends Car and implements Electric, adding batteryCapacity and implementing the methods. In the
Main class, a Tesla object is created and its methods are called to show how it works. In this way these
classes and interfaces work together to create a flexible and reusable code structure in Java.
Output: