Writing Classes � We've been using predefined classes. Now we will learn to write our own classes to define Writing Classes in Java objects � Chapter 4 focuses on: � class definitions Selim Aksoy � encapsulation and Java modifiers Bilkent University � method declaration, invocation, and parameter passing Department of Computer Engineering � method overloading saksoy@cs.bilkent.edu.tr � method decomposition Spring 2004 CS 111 2 Objects Classes � An object has: � A class is a blueprint of an object � state - descriptive characteristics � It is the model or pattern from which objects � behaviors - what it can do (or what can be done are created to it) � For example, consider a coin that can be � For example, the String class is used to flipped so that it's face shows either "heads" define String objects or "tails" � Each String object contains specific � The state of the coin is its current face (heads or tails) characters (its state) � The behavior of the coin is that it can be � Each String object can perform services flipped (behaviors) such as toUpperCase � Note that the behavior of the coin might change its state Spring 2004 CS 111 3 Spring 2004 CS 111 4 Classes Classes � The String class was provided for us � A class contains data declarations and by the Java standard class library method declarations � But we can also write our own classes int x, y; Data declarations that define specific objects that we char ch; need � For example, suppose we want to write a program that simulates the flipping of Method declarations a coin � We can write a Coin class to represent a coin object Spring 2004 CS 111 5 Spring 2004 CS 111 6
The Coin Class Example import java.util.Random; � In our Coin class we could define the public class Coin { private final int HEADS = 0; following data: private final int TAILS = 1; private int face; //----------------------------------------------------------------- � face , an integer that represents the current face // Sets up the coin by flipping it initially. //----------------------------------------------------------------- public Coin () � HEADS and TAILS , integer constants that { flip(); } //----------------------------------------------------------------- represent the two possible states // Flips the coin by randomly choosing a face value. //----------------------------------------------------------------- public void flip () � We might also define the following methods: { face = ( int ) (Math.random() * 2); } � a Coin constructor, to initialize the object //----------------------------------------------------------------- // Returns true if the current face of the coin is heads. //----------------------------------------------------------------- public boolean isHeads () � a flip method, to flip the coin { return (face == HEADS); } � a isHeads method, to determine if the current //----------------------------------------------------------------- // Returns the current face of the coin as a string. //----------------------------------------------------------------- face is heads public String toString() { String faceName; � a toString method, to return a string if (face == HEADS) faceName = "Heads"; else description for printing faceName = "Tails"; return faceName; } } Spring 2004 CS 111 7 Spring 2004 CS 111 8 Example The Coin Class public class CountFlips � Note that the CountFlips program { //----------------------------------------------------------------- // Flips a coin multiple times and counts the number of heads did not use the toString method // and tails that result. //----------------------------------------------------------------- public static void main (String[] args) { � A program will not necessarily use final int NUM_FLIPS = 1000; int heads = 0, tails = 0; every service provided by an object Coin myCoin = new Coin(); // instantiate the Coin object for ( int count=1; count <= NUM_FLIPS; count++) � Once the Coin class has been defined, { myCoin.flip(); we can use it again in other programs if (myCoin.isHeads()) heads++; else as needed tails++; } System.out.println ("The number flips: " + NUM_FLIPS); System.out.println ("The number of heads: " + heads); System.out.println ("The number of tails: " + tails); } } Spring 2004 CS 111 9 Spring 2004 CS 111 10 Data Scope Instance Data � The face variable in the Coin class is called � The scope of data is the area in a instance data because each instance (object) program in which that data can be used of the Coin class has its own (referenced) � A class declares the type of the data, but it � Data declared at the class level can be does not reserve any memory space for it � Every time a Coin object is created, a new used by all methods in that class face variable is created as well � Data declared within a method can be � The objects of a class share the method used only in that method definitions, but each has its own data space � Data declared within a method is called � That is the only way two objects can have different states local data Spring 2004 CS 111 11 Spring 2004 CS 111 12
Example Instance Data public class FlipRace { //----------------------------------------------------------------- coin1 // Flips two coins until one of them comes up heads three times class Coin // in a row. //----------------------------------------------------------------- public static void main (String[] args) { final int GOAL = 3; int count1 = 0, count2 = 0; 0 int face; face // Create two separate coin objects Coin coin1 = new Coin(); Coin coin2 = new Coin(); while (count1 < GOAL && count2 < GOAL) { coin1.flip(); coin2.flip(); coin2 // Print the flip results (uses Coin's toString method) System.out.print ("Coin 1: " + coin1); System.out.println (" Coin 2: " + coin2); // Increment or reset the counters count1 = (coin1.isHeads()) ? count1+1 : 0; count2 = (coin2.isHeads()) ? count2+1 : 0; 1 } face // Determine the winner if (count1 < GOAL) System.out.println ("Coin 2 Wins!"); else if (count2 < GOAL) System.out.println ("Coin 1 Wins!"); else System.out.println ("It's a TIE!"); } } Spring 2004 CS 111 13 Spring 2004 CS 111 14 UML Diagrams UML Class Diagrams � UML stands for the Unified Modeling � A UML class diagram for the FlipRace Language program: � UML diagrams show relationships among classes and objects Fl i pRac e Coi n 1 2 � A UML class diagram consists of one or f ac e : i nt m ai n ( ar gs : St r i ng[ ] ) : more classes, each with sections for the voi d f l i p( ) : voi d class name, attributes, and methods i s H e ads ( ) : bool e an t oSt r i ng( ) : St r i ng � Lines between classes represent associations � Associations can show multiplicity Spring 2004 CS 111 15 Spring 2004 CS 111 16 UML Diagrams Encapsulation � We can take one of two views of an object: � A UML object diagram consists of one � internal - the variables the object holds and the or more instantiated objects. methods that make the object useful � external - the services that an object provides � It is a snapshot of the objects during an and how the object interacts executing program, showing data � From the external view, an object is an encapsulated entity, providing a set of values specific services � These services define the interface to the c oi n1 : Coi n c oi n2 : Coi n object f ac e = 0 f ac e = 1 � Recall from Chapter 2 that an object is an abstraction , hiding details from the rest of the system Spring 2004 CS 111 17 Spring 2004 CS 111 18
Recommend
More recommend