Tuesday, 29 August 2017

Java Program demonstrates how to establish this class hierarchy

Java Program demonstrates how to establish this class hierarchy

The abstract vegetable class has three subclasses named Potato, Brinjal and Tomato.

Write a java prog. That demonstrates how to establish this class hierarchy.

Declare one instance variable of type String that indicates the color of a vegetable.

Crete and display instances of these objects.

Override the toString() method of object to return a string with the name of vegetable and its color.

Program

abstract class Vegetable
{
String color;
public String toString()
{  return getClass().getName() +"  " + color; }
}
class Potato extends Vegetable
{
Potato()
{   color = "Creme";    }
}
class Brinjal extends Vegetable
{
Brinjal()
{   color = "Violet";    }
}
class Tomato extends Vegetable
{
Tomato()
{   color = "Red";    }
class M3
{
public static void main(String args[])
{
Vegetable v = new Potato();
System.out.println(v);
v= new Brinjal();
System.out.println(v);
v= new Tomato();
System.out.println(v);
}

}     

Output

class hierarchy java core

0 comments:

Post a Comment