0% found this document useful (0 votes)
9 views

Inheritance

Inheritance in Java allows a subclass to inherit properties and methods from a superclass, promoting code reusability and establishing class relationships. The 'extends' keyword is used to declare inheritance, as demonstrated with the Vehicle superclass and Car subclass example. The document includes code snippets illustrating how to create objects and access inherited methods and fields.

Uploaded by

Sakshi Takwale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Inheritance

Inheritance in Java allows a subclass to inherit properties and methods from a superclass, promoting code reusability and establishing class relationships. The 'extends' keyword is used to declare inheritance, as demonstrated with the Vehicle superclass and Car subclass example. The document includes code snippets illustrating how to create objects and access inherited methods and fields.

Uploaded by

Sakshi Takwale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Inheritance

Inheritance in Java is a fundamental concept of Object-Oriented Programming (OOP) that allows a


new class (called the subclass or child class) to inherit properties and behaviors (fields and methods)
from an existing class (called the superclass or parent class). This promotes code reusability and
helps in establishing a relationship between different classes.

Key Points:

1. Superclass (Parent class): The class whose properties and methods are inherited.

2. Subclass (Child class): The class that inherits the properties and methods from the
superclass.

3. extends keyword: Used to declare inheritance in Java.

// Superclass (Parent class)

class Vehicle {

// Field

String brand;

// Constructor

public Vehicle(String brand) {

this.brand = brand;

// Method

public void startEngine() {

System.out.println("The engine is starting...");

// Subclass (Child class)

class Car extends Vehicle {

// Constructor of the Car class

public Car(String brand) {


// Calling the constructor of the superclass (Vehicle)

super(brand);

// Method specific to the Car class

public void honk() {

System.out.println("The car horn goes beep beep!");

public class Main {

public static void main(String[] args) {

// Creating an object of the Car class

Car myCar = new Car("Toyota");

// Accessing the inherited field and method from Vehicle

System.out.println("Car brand: " + myCar.brand);

myCar.startEngine(); // Inherited method from Vehicle

// Calling the Car-specific method

myCar.honk(); // Method specific to the Car class

You might also like