ShandyNantz/CIS397HW4

From MCIS Wiki

Jump to: navigation, search

Abstract Classes


Abstract classes are a class where instantiation is not allowed - the user cannot use the keyword new to make any new objects. Usually abstract clasess are used to define a catagory or object that is so large that a general outline is needed first to describe it and then it can be broken down into other classes that better define all the smaller parts.

For my example of how abstract classes work, I have made a root abstract class called Dinosaur. In this class I have defined several instance variables:

protected boolean gender; 
protected float weight;
protected boolean plantEater;
protected boolean eating;

By making them protected they are visable to all the subclasses. Also with this class I have defines several methods all of which say something about a Dinosaur and also something that all Dinosaurs have in common.

public abstract void eating();	
public abstract void sleeping();	
public abstract float getWeight();	
public abstract boolean getGender();

Now, all I have to do to use this abstract class is to define a subclass using the keywords extends and within this class I have to define and give code to all the methods described in Dinosaur. Also, by doing it this way, I can define the instance variables in the abstract class and will not have to define them again repetatively in all the subclasses. The subclasses that I created for this example are Tyrannosaurus and Plantasaurus.

Finally, for my example, I have created an array of Dinosaurs along with two Dinosaur objects and then I placed those objects within the array and printed out some string explaining if the Dinosaurs we eating or sleeping. It's also interesting to see that with a class structure like this I can create an array defined as Dinosaurs but still hold objects of many different types that inherate from the Super class.

Tyrannosaurus ty = new Tyrannosaurus( true, (float) 982.212, false, true );		
Plantasuarus p = new Plantasuarus( false, (float)492.122, true, false);		
Dinosaurs [] myDinos = { ty, p };

So the above code works just fine and compiles without any errors!!

Personal tools