Abstract Class Inheritance & Overrides in Java


Create a Java program to demonstrate abstract class inheritance and method overriding

  • The Fruit class is declared as abstract with an abstract method displayTaste().
  • The Apple and Orange classes extend the Fruit class and provide their own implementations for the displayTaste() method.
  • In the main method, objects of Apple and Orange are created and stored in references of type Fruit.
  • When the displayTaste() method is called on these objects, the overridden version of the method in the respective subclass (Apple or Orange) is invoked, printing the appropriate message about the taste of the fruit.

Source Code

abstract class Fruit
{
	abstract void displayTaste();
}
 
class Apple extends Fruit
{
	@Override
	void displayTaste()
	{
		System.out.println("Apple is sweet");
	}
}
 
class Orange extends Fruit
{
	@Override
	void displayTaste()
	{
		System.out.println("Orange is tangy");
	}
}
 
public class Main
{
	public static void main(String[] args)
	{
		Fruit apple = new Apple();
		Fruit orange = new Orange();
 
		apple.displayTaste();
		orange.displayTaste();
	}
}

Output

Apple is sweet
Orange is tangy