Superclasses and Subclasses in Java

Java Classes & Inheritance

? What is a Class?

A class is like a blueprint or a plan in Java. It helps us create things (objects) with specific properties (variables) and actions (methods).

Superclass

Think of a superclass as the main or general blueprint. It defines common properties and methods that multiple things (objects) might have.

class Animal {
    String name;
    int age;
    
    void makeSound() {
        System.out.println("Some generic animal sound");
    }
}

Here, Animal is a superclass with properties like name and age, and a method makeSound.

Subclass

A subclass is like a specialized version that adds more details or customizes the general blueprint. It inherits properties and methods from the superclass but can also have its own unique ones.

class Dog extends Animal {
    void bark() {
        System.out.println("Woof! Woof!");
    }
}

Here, Dog is a subclass of Animal. It inherits name, age, and makeSound from Animal and adds its own method bark.

Using Superclasses and Subclasses

Now, we can create objects based on these blueprints.

public class Main {
    public static void main(String[] args) {
        // Creating an object of the superclass
        Animal genericAnimal = new Animal();
        genericAnimal.name = "Generic Animal";
        genericAnimal.age = 5;
        genericAnimal.makeSound();  // Output: Some generic animal sound

        // Creating an object of the subclass
        Dog myDog = new Dog();
        myDog.name = "Buddy";
        myDog.age = 3;
        myDog.makeSound();  // Output: Some generic animal sound
        myDog.bark();       // Output: Woof! Woof!
    }
}

💡 We can use objects of both the superclass and the subclass.

Have Questions?

If you have any question then comment below - We will answer your questions.

📝 And do not forget to follow us!

Post a Comment

0 Comments