Credits

Monday, December 13, 2010

Java's Use of Abstract Classes

Abstract classes in Java are used as base class for other classes. They cannot however be instantiated but are allowed to be parent of child classes. Abstract classes may or may not contain abstract methods but abstract methods must be in abstract class.

The programs below have used abstract methods and class to allow different actions for different objects.

[+/-] show/hide


/*sample program on abstract classes
* parent class to program files : abstractDog, abstractSnake, abstractCow
called by abstractAnimalRefence class
*/

public abstract class AbstractAnimal {
private String name;



public AbstractAnimal(String nm)
{
name = nm;
}

public abstract void speak();

public String getName()
{
return name;
}
}


/*sample program on abstract classes using array of objects
* The calling program of abstract classes
*/
import javax.swing.*;
public class AbstractAnimalReferencev2
{
public static void main(String args[]){
String pet= " ";
AbstractAnimal[] ref = new AbstractAnimal[3];

abstractCow aCow= new abstractCow("Daisy");
abstractDog aDog= new abstractDog("Pixel");
abstractSnake aSnake= new abstractSnake("Lily");


ref[0] = aCow; //abstract or not, a reference can be made to a superclass
ref[1] = aDog;
ref[2] = aSnake;



for ( int x =0;x<3;x++) { if (x == 0) pet=" cow "; if (x == 1) pet=" dog "; if (x == 2) pet=" snake "; JOptionPane.showMessageDialog(null,"My "+ pet + " named "+ref[x].getName()+" says "); ref[x].speak(); } } } /*sample program on abstract classes called by abstractAnimalRefence class */ import javax.swing.*; public class abstractCow extends AbstractAnimal{ public abstractCow(String nm) { super(nm); } public void speak(){ JOptionPane.showMessageDialog(null," Moo! Moo! Moo!"); } } /*sample program on abstract classes called by abstractAnimalRefence class */ import javax.swing.*; public class abstractDog extends AbstractAnimal{ public abstractDog(String nm) { super(nm); } public void speak(){ JOptionPane.showMessageDialog(null," WOOF! Woof! Woof!"); } } /*sample program on abstract classes called by abstractAnimalRefence class */ import javax.swing.*; public class abstractSnake extends AbstractAnimal{ public abstractSnake(String nm) { super(nm); } public void speak(){ JOptionPane.showMessageDialog(null," Sss! Sss! Sss!"); } }

AddThis