Program Definition 14::
The abstract Fruit class has four subclasses named Apple, Banana, Orange and Strawberry. Write an application that demonstrates how to establish this class hierarchy. Declare one instance variable of type string that indicates the color of a fruit. Create and display instances of these object. Override the toString() method of Object to return a string with the name of the fruit and its color.
abstract class Fruit
{
String color;
Fruit( String c )
{
color = c ;
}
abstract public String toString();
}
class Apple extends Fruit
{
Apple( String c )
{
super(c);
}
public String toString()
{
return "Apple color :: " + color ;
}
}
class Banana extends Fruit
{
Banana( String c )
{
super(c);
}
public String toString()
{
return "Banana color :: " + color ;
}
}
class Orange extends Fruit
{
Orange( String c )
{
super(c);
}
public String toString()
{
return "Orange color :: " + color ;
}
}
class Stawberry extends Fruit
{
Stawberry( String c )
{
super(c);
}
public String toString()
{
return "Stawberry color :: " + color ;
}
}
class TestFruit
{
public static void main( String args[] )
{
Fruit f[] = new Fruit[4];
f[ 0 ] = new Apple("Red");
f[ 1 ] = new Banana("Yellow");
f[ 2 ] = new Orange("Orange");
f[ 3 ] = new Stawberry("Red");
for( Fruit f1 : f )
{
System.out.println(f1.toString());
}
}
}
/*
D:\JAVA >javac TestFruit.java
D:\JAVA >java TestFruit
Apple color :: Red
Banana color :: Yellow
Orange color :: Orange
Stawberry color :: Red
*/
0 comments :