seem 34601 java – basic introduction, classes and objects

27
SEEM 3460 1 Java – Basic Introduction, Classes and Objects

Upload: sharyl-bridges

Post on 19-Jan-2016

219 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: SEEM 34601 Java – Basic Introduction, Classes and Objects

SEEM 3460 1

Java – Basic Introduction, Classes and Objects

Page 2: SEEM 34601 Java – Basic Introduction, Classes and Objects

SEEM 3460 2SEEM 3460 2

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

Page 3: SEEM 34601 Java – Basic Introduction, Classes and Objects

SEEM 3460 3SEEM 3460 3

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

Page 4: SEEM 34601 Java – Basic Introduction, Classes and Objects

SEEM 3460 4SEEM 3460 4

Classes A class can contain data declarations and

method declarations

int size, weight;char category;

Data declarations

Method declarations

Page 5: SEEM 34601 Java – Basic Introduction, Classes and Objects

SEEM 3460 5SEEM 3460 5

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

Page 6: SEEM 34601 Java – Basic Introduction, Classes and Objects

SEEM 3460 6SEEM 3460 6

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

Page 7: SEEM 34601 Java – Basic Introduction, Classes and Objects

General Design of Objects and Classes

SEEM 3460 7

• In general, we should first declare an object reference

• Then, we allocate memory for the object

SEEM 3460 7

AClass obj1;

obj1 = new AClass();

The first line declares an object reference obj1 belonging to a class called AClass

Data fields for obj1obj1

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

Page 8: SEEM 34601 Java – Basic Introduction, Classes and Objects

SEEM 3460 8SEEM 3460 8

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:

General Design of Objects and Classes

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();

Page 9: SEEM 34601 Java – Basic Introduction, Classes and Objects

SEEM 3460 9SEEM 3460 9

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 isa special method that sets up the object

Page 10: SEEM 34601 Java – Basic Introduction, Classes and Objects

SEEM 3460 10SEEM 3460 10

Creating Objects - Instantiation Creating an object is called instantiation

An object is an instance of a particular class

Page 11: SEEM 34601 Java – Basic Introduction, Classes and Objects

SEEM 3460 11SEEM 3460 11

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

Page 12: SEEM 34601 Java – Basic Introduction, Classes and Objects

SEEM 3460 1212

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

"Steve Jobs"title1

num1 38

Page 13: SEEM 34601 Java – Basic Introduction, Classes and Objects

SEEM 3460 13SEEM 3460 13

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

A Complete Example of Classes and Objects

Page 14: SEEM 34601 Java – Basic Introduction, Classes and Objects

SEEM 3460 14SEEM 3460 14

Download the java source files with command

Open the terminal, and input the command below

“wget http://www.se.cuhk.edu.hk/~seem3460/tutorial/lab/RollingDice.java”

“wget http://www.se.cuhk.edu.hk/~seem3460/tutorial/lab/Die.java”

A Complete Example of Classes and Objects

Page 15: SEEM 34601 Java – Basic Introduction, Classes and Objects

SEEM 3460 15SEEM 3460 15

//*************************************************************// 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);

Page 16: SEEM 34601 Java – Basic Introduction, Classes and Objects

SEEM 3460 16SEEM 3460 16

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); }}

Page 17: SEEM 34601 Java – Basic Introduction, Classes and Objects

SEEM 3460 17SEEM 3460 17

//*************************************************************// 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; }

Page 18: SEEM 34601 Java – Basic Introduction, Classes and Objects

SEEM 3460 18SEEM 3460 18

//----------------------------------------------------------------- // 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; }

Page 19: SEEM 34601 Java – Basic Introduction, Classes and Objects

SEEM 3460 19SEEM 3460 19

//----------------------------------------------------------------- // Returns a string representation of this die. //----------------------------------------------------------------- public String toString() { String result = Integer.toString(faceValue);

return result; }}

Page 20: SEEM 34601 Java – Basic Introduction, Classes and Objects

SEEM 3460 20SEEM 3460 20

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

Page 21: SEEM 34601 Java – Basic Introduction, Classes and Objects

SEEM 3460 21SEEM 3460 21

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

Page 22: SEEM 34601 Java – Basic Introduction, Classes and Objects

SEEM 3460 22SEEM 3460 22

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

Page 23: SEEM 34601 Java – Basic Introduction, Classes and Objects

SEEM 3460 23SEEM 3460 23

Instance Data We can depict the two Die objects from the

RollingDice program as follows:

die1 5faceValue

die2 2faceValue

Each object maintains its own faceValue variable, and thus its own state

Page 24: SEEM 34601 Java – Basic Introduction, Classes and Objects

SEEM 3460 24SEEM 3460 24

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

Page 25: SEEM 34601 Java – Basic Introduction, Classes and Objects

SEEM 3460 25SEEM 3460 25

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

Page 26: SEEM 34601 Java – Basic Introduction, Classes and Objects

SEEM 3460 26SEEM 3460 26

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

Page 27: SEEM 34601 Java – Basic Introduction, Classes and Objects

SEEM 3460 27SEEM 3460 27

RollingDice.java - Sample Execution

The following is a sample execution of RollingDice.class

cuse93> java RollingDiceDie One: 6, Die Two: 1Die One: 4, Die Two: 4Sum: 8Die One: 3, Die Two: 2New sum: 5