Program Definition 16 ::
Interface Material defines a set of String constants for various materials. Abstract class MaterialObject has one instance variable named material of type String. These records the material used to construct the object. Classes Ball, Coin and Ring extend MaterialObject . The constructor initializes the material variable. Class MaterialObjects instantiates these three classes. A different material is passed to each constructor. Display material of each object.
interface Material
{
String gold = "Gold";
String silver = "Silver";
String rubber = "Rubber";
}
abstract class MaterialObject implements Material
{
String material;
MaterialObject( String m )
{
material = m ;
}
abstract public void display();
}
class Ball extends MaterialObject
{
Ball( String m )
{
super( m );
}
public void display()
{
System.out.println( "Ball Material :: " + material );
}
}
class Coin extends MaterialObject
{
Coin( String m )
{
super(m);
}
public void display()
{
System.out.println( "Coin Material :: " + material );
}
}
class Ring extends MaterialObject
{
Ring( String m )
{
super( m );
}
public void display()
{
System.out.println( "Ring Material :: " + material );
}
}
class TestMaterial
{
public static void main( String args[])
{
MaterialObject[] m = new MaterialObject[3];
m[ 0 ] = new Ring(Material.gold);
m[ 1 ] = new Ball(Material.rubber);
m[ 2 ] = new Coin(Material.silver);
for ( MaterialObject m1 : m )
{
m1.display();
}
}
}
/*
D:\MCA\JAVA>javac TestMaterial.java
D:\MCA\JAVA>java TestMaterial
Ring Material :: Gold
Ball Material :: Rubber
Coin Material :: Silver
*/
0 comments :