Java – Basic Introduction, Classes and Objects SEEM 3460 1 Writing Classes Now we will begin to design programs that rely on classes that we write ourselves The class that contains the main method is just the starting point of a program True object-oriented programming is based on defining classes that represent objects with well-defined characteristics and functionality SEEM 3460 2 Designing Classes and Objects An object has state and behavior Consider a six-sided die (singular of dice) It’s state can be defined as which face is showing It’s primary behavior is that it can be rolled We can represent a die in software by designing a class called Die that models this state and behavior The class serves as the blueprint for a die object We can then instantiate as many die objects as we need for any particular program SEEM 3460 3 Classes A class can contain data declarations and method declarations int size, weight; char category; Data declarations Method declarations SEEM 3460 4 Classes The values of the data define the state of an object created from the class The functionality of the methods define the behaviors of the object For our Die class, we might declare an integer that represents the current value showing on the face One of the methods would “roll” the die by setting that value to a random number between one and six SEEM 3460 5 Classes In general, a class share some similarities with structures in C Recall that a structure in C is a user-defined data type composed of some data fields and each field belongs to a certain data type or another structure type A class is also composed of some data fields. In addition to it, a class is also associated with some methods SEEM 3460 6 General Design of Objects and Classes • In general, we should first declare an object reference • Then, we allocate memory for the object AClass obj1; obj1 = new AClass(); obj1 The first line declares an object reference obj1 belonging to a class called AClass The second line uses the new operator to allocate some memory for an object (under the class AClass) and lets obj1 points to it The second line also invokes the AClass constructor, if exists, to initialize the data in the object Data fields for obj1 SEEM 3460 7 General Design of Objects and Classes Similar to structures in C, one can access the data fields of an object via the dot operator For example, suppose in the class AClass, there are some data fields declared such as field1 and field2. Then, we can access field1 in obj1 via: obj1.field1 = 100; We can process an object by a method specified in the corresponding class via dot operator Suppose in the class AClass, there are some methods declared such as method1 and method2 Then we can process the object obj1 by method1 via: a_value = obj1.method1(); SEEM 3460 8 Creating Objects – Another Example A variable holds either a primitive type or a reference to an object A class name can be used as a type to declare an object reference variable String title; An object reference variable holds the address of an object The object itself must be created separately Generally, we use the new operator to create an object title = new String ("Java Software Solutions"); This calls the String constructor, which is a special method that sets up the object SEEM 3460 9 Creating Objects - Instantiation Creating an object is called instantiation An object is an instance of a particular class SEEM 3460 10 Invoking Methods We've seen that once an object has been instantiated, we can use the dot operator to invoke its methods count = title.length() A method may return a value, which can be used in an assignment or expression A method invocation can be thought of as asking an object to perform a service SEEM 3460 11 Object References Note that a primitive variable contains the value itself, but an object variable contains the address of the object An object reference can be thought of as a pointer to the location of the object Rather than dealing with arbitrary addresses, we often depict a reference graphically num1 38 title1 "Steve Jobs" SEEM 3460 12 A Complete Example of Classes and Objects Return to the example of our Die class For our Die class, we might declare an integer that represents the current value showing on the face One of the methods would “roll” the die by setting that value to a random number between one and six We’ll want to design the Die class with other data and methods to make it a versatile and reusable resource SEEM 3460 13 A Complete Example of Classes and Objects Download the java source files with command Open the terminal, and input the command below “wget http://www.se.cuhk.edu.hk/~seem3460/tu torial/lab/RollingDice.java” “wget http://www.se.cuhk.edu.hk/~seem3460/tutorial/l ab/Die.java” SEEM 3460 14 //************************************************************* // RollingDice.java // // Demonstrates the creation and use of a user-defined class. //************************************************************* public class RollingDice { //----------------------------------------------------------------// Creates two Die objects and rolls them several times. //----------------------------------------------------------------public static void main (String[] args) { Die die1, die2; int sum; die1 = new Die(); die2 = new Die(); die1.roll(); die2.roll(); System.out.println ("Die One: " + die1 + ", Die Two: " + die2); SEEM 3460 15 die1.roll(); die2.setFaceValue(4); System.out.println ("Die One: " + die1 + ", Die Two: " + die2); sum = die1.getFaceValue() + die2.getFaceValue(); System.out.println ("Sum: " + sum); } } sum = die1.roll() + die2.roll(); System.out.println ("Die One: " + die1 + ", Die Two: " + die2); System.out.println ("New sum: " + sum); SEEM 3460 16 //************************************************************* // Die.java // // Represents one die (singular of dice) with faces showing values // between 1 and 6. //************************************************************* public class Die { private final int MAX = 6; // maximum face value private int faceValue; // current value showing on the die //----------------------------------------------------------------// Constructor: Sets the initial face value. //----------------------------------------------------------------public Die() { faceValue = 1; } SEEM 3460 17 //----------------------------------------------------------------// Rolls the die and returns the result. //----------------------------------------------------------------public int roll() { faceValue = (int)(Math.random() * MAX) + 1; return faceValue; } //----------------------------------------------------------------// Face value mutator. //----------------------------------------------------------------public void setFaceValue (int value) { faceValue = value; } //----------------------------------------------------------------// Face value accessor. //----------------------------------------------------------------public int getFaceValue() { return faceValue; } SEEM 3460 18 //----------------------------------------------------------------// Returns a string representation of this die. //----------------------------------------------------------------public String toString() { String result = Integer.toString(faceValue); } } return result; SEEM 3460 19 The Die Class The Die class contains two data values a constant MAX that represents the maximum face value an integer faceValue that represents the current face value The roll method uses the random method of the Math class to determine a new face value There are also methods to explicitly set and retrieve the current face value at any time SEEM 3460 20 Data Scope The scope of data is the area in a program in which that data can be referenced (used) Data declared at the class level can be referenced by all methods in that class Data declared within a method can be used only in that method Data declared within a method is called local data In the Die class, the variable result is declared inside the toString method -- it is local to that method and cannot be referenced anywhere else SEEM 3460 21 Instance Data The faceValue variable in the Die class is called instance data because each instance (object) that is created has its own version of it A class declares the type of the data, but it does not reserve any memory space for it Every time a Die object is created, a new faceValue variable is created as well The objects of a class share the method definitions, but each object has its own data space That's the only way two objects can have different states SEEM 3460 22 Instance Data We can depict the two Die objects from the RollingDice program as follows: die1 faceValue 5 die2 faceValue 2 Each object maintains its own faceValue variable, and thus its own state SEEM 3460 23 The toString Method All classes that represent objects should define a toString method The toString method returns a character string that represents the object in some way It is called automatically when an object is concatenated to a string or when it is passed to the println method SEEM 3460 24 Constructors A constructor is a special method that is used to set up an object when it is initially created A constructor has the same name as the class and it has no return data type The Die constructor is used to set the initial face value of each new die object to one We examine constructors in more detail later SEEM 3460 25 RollingDice.java - Compilation Assume that both RollingDice.java and Die.java are stored under the same directory in an Unix account To compile under Unix platform, we can simply compile the RollingDice.java: cuse93> javac RollingDice.java The compiler will first compile RollingDice.java. When it finds out that it needs to make use of the class Die.java. It will automatically compile Die.java If the compilation is successful, you can find two bytecodes, namely, RollingDice.class and Die.class If there is compilation error, the error message will be displayed on the terminal. If you wish to make the error message be displayed screen by screen, you can compile in the following way: cuse93> javac RollingDice.java |& more SEEM 3460 26 RollingDice.java - Sample Execution The following is a sample execution of RollingDice.class cuse93> java RollingDice Die One: 6, Die Two: 1 Die One: 4, Die Two: 4 Sum: 8 Die One: 3, Die Two: 2 New sum: 5 SEEM 3460 27