Abstract Classes in Java

I like abstract classes more then generic polymorphic classes or interfaces. I tend to view abstract classes somewhere in-between polymorphism and interfaces.

Here is a link to the java docs on abstract methods and classes.
http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html

If you looked at my Polymorphism in Java post this should like familiar to you. An abstract class works in the same fashion as a parent class in polymorphism but you can also reference undefined methods like in interfaces. The keyword in this code is “abstract”.

Here is my base class, Animal

package Abstract;

abstract class Animal {
	private String name;
	private Type type;
	
	public enum Type{
		herbivore,
		carnivore,
		omnivor
	}
	
	public Animal(){
		this.name = null;
		this.type = Type.omnivor;
	}
	
	public Animal(Type type){
		this.type = type;
	}
	
	public String getName(){ return this.name; }
	public Type   getType(){ return this.type; }
	
	abstract public String speak();
}

Now let’s derive another class from the abstract class Animals. The keyword here like in poloymorphism is “extends”.

public class Duck extends Animal {

	public Duck(){
		super();
	}
	
	@Override
	public String speak() {
		return("aflac");
	}
}

I also made another kind an animal and the code of the class is set up very much the same as the duck class.

package Abstract;

public class Cow extends Animal{
	
	public Cow(){
		super(Type.herbivore);
	} 
	
	@Override
	public String speak() {
		return ("Moo");
	}
}

Here is a simple test case on how to use the cow and duck objects.

package Abstract;

public class testAbstract {
	public static void main(String[] args){
		
		Cow myCow = new Cow();
		System.out.println("The cow says: " + myCow.speak() );
		
		Duck myDuck = new Duck();
		System.out.println( "The duck says: " + myDuck.speak() );
	}
}

Sample output:
The cow says: Moo
The duck says: aflac

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s