Subclass Method Overrides Generic Class Method In Java
Create a Java program to demonstrate method overriding with a subclass that overrides a method from a generic class
The code defines a generic class Box that can hold an item of any type T, and a subclass StringBox that specializes the generic Box class to hold String objects. The StringBox class extends Box, which means it is specifically designed to hold String items. Here's an explanation of the code:
- Box is a generic class with a generic type parameter T. It has a field item of type T to store the item.
- The Box class has a constructor that takes an item of type T and sets it as the item field.
- It also has a display method that displays the item stored in the Box.
- StringBox is a subclass of Box, which means it is a specialized version of the Box class designed to hold String items. It provides a constructor that takes a String item and uses super(item) to call the constructor of the superclass Box.
- In the StringBox class, you override the display method to add specific behavior. First, it calls super.display() to display the String item stored in the StringBox, and then it appends the length of the string to the output.
- In the Main class, you create an instance of StringBox named box with the item "Java Exercise" and call its display method.
Source Code
class Box<T>
{
T item;
Box(T item)
{
this.item = item;
}
void display()
{
System.out.println("Item : " + item);
}
}
class StringBox extends Box<String>
{
StringBox(String item)
{
super(item);
}
@Override
void display()
{
super.display();
System.out.println("Length : " + item.length());
}
}
public class Main
{
public static void main(String[] args)
{
StringBox box = new StringBox("Java Exercise");
box.display();
}
}
Output
Item : Java Exercise
Length : 13