Saturday 29 September 2012

Java Practical - 19



    Program Definition 19 ::
 
    The abstract class Fish declares one abstract method named display().   It also has two abstract subclasses named FreshWaterFish and SaltWaterFish.  Define three concrete subclasses named Trout, Flounder and Tuna.  Trout extends FreshWaterFish and Flounder and Tuna both extends SaltWaterFish.  Write a main() method which creates an array of type Fish.  Instantiate and assign different types of Fish to the elements of the array.  Display the name of fish which is of type SaltWaterFish using display() method.




abstract class Fish
{
String name;
abstract public void display();
}

abstract class SaltWaterFish extends Fish
{
}

abstract class FreshWaterFish extends Fish
{
}

class Trout extends FreshWaterFish
{
Trout( String n )
{
this.name = n;
}
public void display()
{
System.out.println( name );
}
}

class Flounder extends SaltWaterFish
{
Flounder( String n )
{
this.name = n ;
}
public void display()
{
System.out.println( name );
}
}

class Tuna extends SaltWaterFish
{
Tuna( String n )
{
this.name = n ;
}
public void display()
{
System.out.println( name );
}
}


class Prog19
{
public static void main( String args[] )
{
Fish fish[] = new Fish[3] ;

fish [ 0 ] = new Trout("Trout");
fish [ 1 ] = new Flounder("Flounder");
fish [ 2 ] = new Tuna("Tuna");

for ( Fish f : fish)
{
//finds fish that belongs to SaltWater using instanceOf operator
if ( f instanceof SaltWaterFish)
f.display();
}
}
}

/*

D:\JAVA >javac Prog19.java

D:\JAVA >java Prog19
Flounder
Tuna
*/

Kindly Bookmark and Share it:

0 comments :

Post a Comment

Any Query ? any suggestion ? comment here

 

Recent Post

Recent Comments

© 2010 IamLearningHere Template by MBT