You are on page 1of 1
Powered by AL Copilot In Java, the concepts of subclass and superclass are fundamental to object-oriented programming, Let's dive into what they mean: 1, Superclass (Parent Class): ‘© Asuperclass (also known as a parent class or base class) is an existing class from which other classes can inherit attributes and methods. Itserves as a generalized template that defines common behavior and properties. Members (fields, methods, and nested classes) of the superclass are inherited by its subclasses. ‘The superclass provides a foundation for creating more specialized classes. Example: Consider a Vehicle class with a brand attribute and a honk() method: class Vehicle { protected String brand = "Ford"; // Vehicle attribute public void honk() { Systen.out.printin("Tuut, tuut!"); // Vehicle method ) } 2, Subelass (Child Class): © Asubelass (also called a derived class, child class, or extended class) is a new class created by inheriting features from a superclass. © It specializes the behavior of the superclass by adding or modifying attributes and methods. © Subclasses can directly access the members of their superclass (except for private members and constructors). © Example: Let's create a Car class that inherits from Vehicle: class Car extends Vehicle { private String modelNane = “Mustang”; // Car attribute public static void main(String[] args) { Car myCar = new Car()3 // Create a Car object myCar-honk();_// Call the honk() method from Vehicle class Systen.out.printIn(nyCar.brand +" " + myCar.modelNane); ) © In this example, car inherits the brand attribute and honk() method from Vehicle. Why use “Inheritance”? + Code Reusability: Inheritance allows you to reuse attributes and methods from an existing class when creating a new class, + Polymorphism: Inherited methods can perform different tasks based on the specific subclass. Remember, if you want to prevent other classes from inheriting from a class, you can use the Final keyword. For instance: final class Vehicle { ... } // Prevents inheritance class Car extends Vehicle { ... } // Generates an error

You might also like