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.