0
0
Javaprogramming~5 mins

Parent and child classes in Java

Choose your learning style9 modes available
Introduction

Parent and child classes help organize code by sharing common features. The child class can use and add to what the parent class has.

When you want to create a general class and then make more specific versions of it.
When many classes share some common behavior or data.
When you want to reuse code to avoid writing the same thing again.
When you want to change or add features in a new class without changing the original.
When modeling real-world things that have a clear hierarchy, like animals and dogs.
Syntax
Java
class ParentClass {
    // parent class code
}

class ChildClass extends ParentClass {
    // child class code
}

The keyword extends is used to create a child class from a parent class.

The child class inherits all public and protected members from the parent class.

Examples
Here, Dog is a child of Animal. It changes the sound method.
Java
class Animal {
    void sound() {
        System.out.println("Some sound");
    }
}

class Dog extends Animal {
    void sound() {
        System.out.println("Bark");
    }
}
Car inherits start() from Vehicle and adds openDoor().
Java
class Vehicle {
    void start() {
        System.out.println("Vehicle started");
    }
}

class Car extends Vehicle {
    void openDoor() {
        System.out.println("Door opened");
    }
}
Sample Program

This program shows a child class overriding a method and also calling the parent's version using super.

Java
class Parent {
    void greet() {
        System.out.println("Hello from Parent");
    }
}

class Child extends Parent {
    void greet() {
        System.out.println("Hello from Child");
    }

    void parentGreet() {
        super.greet();
    }
}

public class Main {
    public static void main(String[] args) {
        Child c = new Child();
        c.greet();
        c.parentGreet();
    }
}
OutputSuccess
Important Notes

Use super to call a parent class method from the child class.

Child classes can override parent methods to change behavior.

Constructors are not inherited but the child can call the parent's constructor.

Summary

Parent and child classes help organize and reuse code.

Use extends to create a child class.

Child classes inherit and can override parent class methods.