80 likes | 106 Views
Learn about Java interfaces, implementing interfaces, and working with array lists to manage ordered groups of objects in your Java programs.
E N D
Interfaces and an Array List Dan Fleck 2007
Java Interfaces • An interface • Specifies methods and constants, but supplies no implementation details • Can be used to specify some desired common behavior that may be useful over many different types of objects • The Java API has many predefined interfaces • Example: java.util.Collection (from Carrano slides)
Java Interfaces • A class that implements an interface must • Include an implements clause • Provide implementations of the methods of the interface • To define an interface • Use the keyword interface instead of class in the header • Provide only method specifications and constants in the interface definition (from Carrano slides)
Example Interface public interface AreaStructure { /** Returns the area of this object. */public double getArea(); /** Returns how may square feet this thing is. */public double getSquareFeet(); }
Building class public class Building implements AreaStructure { private int numFloors; private double floorSquareFeet; private int numDoors; public Building(int floors, int doors, double sqFeetPerFloor) { numFloors = floors; floorSquareFeet = sqFeetPerFloor; numDoors = doors; } public int getNumDoors() { return numDoors; } public double getArea() { return floorSquareFeet *numFloors; } public double getSquareFeet() { return floorSquareFeet; } }
Main class public static void main(String args[]) { Building building1 = new Building(10, 2, 1800.0); AreaStructure area1 = new Building(5, 1, 500.0); System.out.println("Building 1 Area is :"+building1.getArea()); System.out.println("Area1 area is:"+area1.getArea()); System.out.println("Building 1 Doors are: "+building1.getNumDoors()); // This does not work because Java treats the Object as a // AreaStructure which does NOT have a getNumDoors() method!!! System.out.println("Area1 doors are:"+area1.getNumDoors());
Now lets create a List interface A List is an ordered group of Objects that you can request by index. Lists allow duplicate objects. public interface List { // Add to the List// Remove from the List// Remove everything from the list// Is the list empty? // Insert into the list// Get an item from the list}
List Example • See example Program in InterfacesAndLists Netbeans project.