260 likes | 403 Views
Java. Classes. Objectives. Be able to define new classes Be able to define appropriate instance variables Be able to define the usual methods of a class Constructors Accessors Mutators Other Be able to distinguish between static and instance variables and methods
E N D
Java Classes
Objectives • Be able to define new classes • Be able to define appropriate instance variables • Be able to define the usual methods of a class • Constructors • Accessors • Mutators • Other • Be able to distinguish between static and instance variables and methods • Be able to create and call static methods • Be able to create and call instance methods
Classes • Classes encapsulate object types. • In object-centered design we • Reuse old classes where possible • Build new classes when necessary • Each new class that we design and build should have a coherent set of: • Knowledge • Responsibilities
Ice Cream Orders • Suppose you were writing a program for use at an ice cream shop. The program needs to help track what orders are given and when they have been fulfilled. • What are the necessary… • Data? • Number of scoops • Flavor • Order fulfilled (true or false) • Operations? • Create new order • Change fulfilled status • Compute cost
Classes and Objects • Classes describe sets of similar objects by specifying their: • Attributes • Behaviors • Each object has its own copies of the attribute values.
Using Classes • When you use a class object: • The calling program doesn’t know: • How to initialize the object’s data • How to implement the object’s methods • The object itself is responsible for these things. • The calling program accesses them by calling predefined methods.
/** DRIVER PROGRAM * ... appropriate documentation ... */ package c09classes.icecream; public class IceCreamConsole{ //Create a default order IceCreamOrderfirstOrder = new IceCreamOrder(); System.out.println(firstOrder); //Change the number of scoops firstOrder.setScoops(3); System.out.println(firstOrder); //Print out how much the order costs System.out.println(“Collect: “ + firstOrder.getCost()); }
Designing Classes • When we want to work with objects not supported by existing types, we must design a new class. • The key design issues here are: • What classes do we need? • What goes in them (and what doesn’t)?
Information Hiding • When we design a class we distinguish: • the external interface to a class; • the internal implementation of the class. • The principle of information hiding dictates that a class designer: • provide public views of those things that a class user really needs to know; • hide all other details by making them private.
Design using Perspectives • Use an external perspective to specify the public interface to a class. • Use an internal perspective to specify the internals of the class design.
Implementing Classes • Implementing the class attributes • Implementing the class methods: • Constructors • Default-value constructor • Explicit-value constructor • Accessors • Mutators • Other Methods • Copy Constructors
Class Attributes • IceCreamOrder objects will certainly have to encapsulate their own: • # of scoops; • flavor; • fulfilled status • These will be stored as instance variables, which means that each IceCreamOrder object will have its own versions of these values.
Implementing Class Attributes class IceCreamOrder{ private intmyScoops; // number of scoops private String myFlavor; // flavor of ice cream private booleanmyStatus; // order completion // other class stuff here… }
Default-Value Constructor • External View (in the driver): • IceCreamOrder order1 = new IceCreamOrder(); • Internal View (in the class): • /** • * Construct a new IceCreamOrderwith default values • */ • public IceCreamOrder() { • myScoops = 1; • myFlavor = “Vanilla”; • myStatus = false; • }
Constructors as Methods • Constructors are like methods except that: • They have no return type • They are given the same name as the class • They are invoked with new: IceCreamOrder order = new IceCreamOrder(); • Constructors initialize instance variables within the limits set by the invariants. • Constructor methods are often overloaded.
Class Invariants • Objects must maintain the integrity of their internal data. /** * Indicate whether or not the number of scoops is valid. * @param scoops the value to check * @return true if valid, false otherwise */ private booleanisValidScoops(int scoops) { if (scoops < 1) { return false; } return true; }
Explicit-Value Constructor • External View: • IceCreamOrder order1 = new IceCreamOrder(2, “Superman”, false); • Internal View: • /** Construct a new IceCreamOrder • * @param scoops the number of scoops • * @param flavor the ice cream flavor • * @param status the order status • */ • public IceCreamOrder(int scoops, String flavor, boolean status){ • if(isValidScoops(scoops)){ • myScoops = scoops; • } • else{ • System.err.println(“Invalid number of scoops: “ + scoops); • System.exit(-1); • } • myFlavor = flavor; • myStatus = status; • }
Accessor Methods /** @return my number of scoops */ public intgetScoops() { return myScoops; } /** @return my flavor */ public String getFlavor() { return myFlavor; } /** @return my order status */ public booleangetStatus() { return myStatus; }
MutatorMethods /** Change my order completion status */ public void setStatus(boolean status) { myStatus = status; } /** Set a new number of scoops for the order * @param scoops non-negative scoops value */ public void setScoops(int scoops) { if (isValidScoops(scoops)){ myScoops = scoops; } else{ System.err.println(“Could not change number of scoops to “ + scoops); System.exit(-1); } }
Other Methods /** * Print out the value of the order */ public String toString() { String result = myScoops + “ scoop(s) of “ + myFlavor + “ :”; if (myStatus){ result += “ Fulfilled”; } else{ result += “ Unfulfilled”; } return result; }
Copy Constructors • We can’t “copy” objects as follows: • IceCreamOrder order1 = new IceCreamOrder(); • IceCreamOrder order2 = order1; This only copies the reference. • Thus, we must write copy constructors: • IceCreamOrder order1 = new IceCreamOrder(); • IceCreamOrder order2 = order1.copy();
Copying Objects /** * @return a copy of myself */ public IceCreamOrder copy() { return new IceCreamOrder(myScoops, myFlavor, myStatus); }
Instance versus Class Members • Java allows data and methods to be associated with either: • A particular object, or • The class as a whole. • Instance members are defined for each object of a class. • Class members are marked as static and are shared by all objects of a class. • Static methods only reference static data. • Static methods can be called without creating an instance of the class.
Referencing Members • Instance members are referenced using the object identifier. objectIdentifier.memberIdentifier • Class members are referenced using the class identifier. ClassIdentifier.memberIdentifier • Examples: • instance: keyboard.readDouble() • class: Math.PI
Class Data • Instance data is unique for each object of a class • Class data is shared between all objects of a class • Marked as static private static final double PRICE_PER_SCOOP = 1.50; public double getCost() { return myScoops * PRICE_PER_SCOOP; }
Object Interaction • Sometimes objects must interact with each other. /** * Compares one order to another * @param other * @return whether or not the order is bigger than * some other order */ public booleanisBigger(IceCreamOrder other){ return myScoops > other.getScoops(); }