Page 149 - CTS - CSA TP - Volume 2
P. 149
COMPUTER SOFTWARE APPLICATION - CITS
}
void displayDetails() {
System.out.println(“Brand: “ + brand + “, Year: “ + year);
}
}
// Main class
public class VehicleDemo {
public static void main(String[] args) {
// Creating an instance of the Car class
Car car = new Car(“Toyota”, 2022);
// Calling methods from both Vehicle and Car classes
car.displayBrand(); // Output: Brand: Toyota
car.displayDetails(); // Output: Brand: Toyota, Year: 2022
}
}
Output:
Explanation:
• In this program, we have a superclass Vehicle and a subclass Car.
• The Vehicle class has a brand attribute and a displayBrand() method to display the brand.
• The Car class extends the Vehicle class and adds its own attribute year and a displayDetails() method to
display the brand and year.
• In the Vehicle constructor, super(brand) is used to call the superclass constructor and initialize the brand
attribute.
• In the main method, we create an instance of the Car class with the brand “Toyota” and year 2022.
• We call methods from both the Vehicle and Car classes to demonstrate inheritance and method overriding.
• The superclass constructor is invoked using the super keyword within the subclass constructor to initialize
inherited attributes.
This program illustrates how superclasses and subclasses are used in Java to achieve code reuse and inheritance.
The subclass inherits attributes and methods from its superclass and can also provide its own unique attributes
and behaviors. This hierarchical relationship promotes code organization and reusability.
134
CITS : IT & ITES - Computer Software Application - Exercise 100