HomeCoding and ProgrammingWrite a Java Program to demonstrate use of sub class

Write a Java Program to demonstrate use of sub class

Java program that demonstrates the use of a subclass:

// Define a superclass
class Animal {
    protected String name;

    public Animal(String name) {
        this.name = name;
    }

    public void speak() {
        System.out.println(name + " says hello!");
    }
}

// Define a subclass
class Dog extends Animal {
    public Dog(String name) {
        super(name);
    }

    public void speak() {
        System.out.println(name + " barks!");
    }
}

// Main class to test the Animal and Dog classes
public class TestAnimals {
    public static void main(String[] args) {
        // Create an Animal object
        Animal animal = new Animal("Bob");

        // Call the speak method on the Animal object
        animal.speak(); // Output: Bob says hello!

        // Create a Dog object
        Dog dog = new Dog("Rufus");

        // Call the speak method on the Dog object
        dog.speak(); // Output: Rufus barks!
    }
}

In this program, we define a Animal superclass with a name instance variable and a speak method that prints a message to the console. We also define a Dog subclass that extends the Animal class and overrides the speak method to print a different message.

In the main method of the TestAnimals class, we create an Animal object and call its speak method, which prints out the default message. We also create a Dog object and call its speak method, which prints out the message specific to the Dog class.

When we run the program, we see the output:

Bob says hello!
Rufus barks!

This demonstrates the use of a subclass in Java. We can create objects of both the superclass and subclass, and call their methods to perform different actions. The subclass inherits the properties and methods of the superclass, and can also override or add to them as needed.

Naman Raj
Naman Rajhttps://www.digitalnamanji.com/
Hello friends, I am Naman, Technical Author & Founder of Digitalnamanji. I am a Computer Science Engineer and I do coding and programming. At the same time, I am interested in knowing various types of information related to internet and technology and we also teach others.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular