Download Chapter 7 Objects and Classes

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Levels of Abstraction: Software Design
Chapter 7 Objects and Classes
1
Objects and Classes
Motivations
We already know a lot about programming
But Java is Object-Oriented language, so where are all
the objects?
For developing graphical user interfaces and large scale
software systems we need to know OO programming
techniques





Object-oriented programming (OOP) involves
programming using objects
Object: entity that you can manipulate in your programs



Class: construct that defines objects of the same type (set
of objects with the same behaviour)



Data fields: state of an object
Methods: instructions that accesses or modifies the state of an
object
Definition of data fields: properties of defined objects
Definition of methods: behaviours of defined objects
Each object belongs to a class
2
Levels of Abstraction: Software Design



Objects and Classes
Old times: computer programs manipulated primitive
types such as numbers and characters
Manipulating too many of these primitive quantities is
too much for programmers and leads to errors
Solution: Encapsulate routine computations to software
black boxes


Object: entity that you can manipulate in your programs
Class: “blueprint” for the objects
6
Programming with Objects and Classes
UML design
Defining a class
Creating objects using a class and using the objects
Using existing classes in Java API



Class name
Circle
UML Class Diagram
radius: double
Data fields
Circle()
Constructors and
Methods
Circle(newRadius: double)
getArea(): double
circle1: Circle
radius: 10
circle3: Circle
circle2: Circle
radius: 25
UML notation
for objects
radius: 125
10
Classes
A Java class uses variables to define data fields
A class uses methods to define behaviors which
accesses or modifies the data fields
A class provides a special type of methods, known as
constructors, which are used to construct and
initialize objects from the class



Classes
class Circle {
/** The radius of this circle */
double radius = 1.0;
/** Construct a circle object */
Circle() {
}
/** Construct a circle object */
Circle(double newRadius) {
radius = newRadius;
}
/** Return the area of this circle */
double getArea() {
return radius * radius * 3.14159;
}
}
8
11
Circle example

Circle



Properties: radius
Behavior: compute area
Circle class



Data fields: radius
Constructors
Methods: getArea()
Syntax: Class Definition
accessSpecifier class ClassName
{
constructors
methods
fields
}
Example:
public class Circle
{
Circle (double newRadius) { . . . }
getArea() { . . . }
double radius;
. . .
}
Purpose:
To define a class
Data field
Constructors
Where is the
main method?
Method
Constructors
Creating and Using Objects

Circle() {
}
No-args constructor


Declaring object reference variables
Creating objects
Accessing objects
Circle(double newRadius) {
radius = newRadius;
Constructor that takes one
}
double parameter
Constructors are a special kind of methods
that are invoked to construct objects
13
Constructors
Declaring Object Reference Variables

Constructors must have the same name as the class
itself
To declare a reference variable, use the syntax:

Constructors do not have a return type - not even
void
A class may be declared without constructors
ClassName objectRefVar;


In this case, a no-arg constructor with an empty body is
implicitly declared in the class (default constructor)
Example:
Circle myCircle;
14
Syntax: Constructor Definition
17
Creating Objects Using Constructors

accessSpecifier ClassName(parameterType parameterName, . . .)
{
constructor body
}
Example:
public Circle (double radius)
{
. . .
}
Purpose:
To define the behavior of a constructor
Invoking a class constructor using the new operator
to create an object
new ClassName();

To reference an object, assign the object to a reference
variable.
Example:
Circle myCircle;
myCircle = new Circle(5.0);
18
Declaring/Creating Objects in a Single Step
Primitive data types vs. object data types


ClassName objectRefVar = new ClassName();
Example:
Assign object reference
Variables of primitive data types store the actual value
Variables of object types store the reference to the
object
Create an object
Circle myCircle = new Circle();
19
22
Accessing Objects

Referencing the object’s data:
objectRefVar.data
e.g., myCircle.radius

Copying Variables of Primitive Data Types
and Object Types
Primitive type assignment i = j
Before:
After:
i
1
i
2
j
2
j
2
Invoking the object’s method:
Object type assignment c1 = c2
objectRefVar.methodName(arguments)
Before:
e.g., myCircle.getArea()
After:
c1
c1
c2
20
Example: Circle Class and Tester Class
c2
c1: Circle
C2: Circle
c1: Circle
C2: Circle
radius = 5
radius = 9
radius = 5
radius = 9
23
The null Value

Circle1.java – defines a Circle class which can be


used to create Circle objects
TestCircle1.java – a tester class that tests Circle
class by creating Circle objects and invoking methods


Trace the program of TestCircle1.java
What if we forget to create an object and assign the
reference to our object variable?
If a data field of a reference type does not reference any
object, the data field holds a special value: null
Circle c;
double r = c.getRadius();
Compilation
Error
c
21
24
Reference value:
null
The null Value

Default Value for a Data Field
Create an object and initialize the object reference
variable before trying to use it
Circle c;
double r = c.getRadius();
Circle c = new Circle(10);
double d = c.getRadius();
c
Reference value
public class Student {
String name; // name has default value null
int age; // age has default value 0
boolean isScienceMajor; // isScienceMajor has default value false
char gender; //gender has default value (char)0
}
public class Test {
public static void main(String[] args) {
Student student = new Student();
System.out.println("name? " + student.name);
System.out.println("age? " + student.age);
System.out.println("isScienceMajor? " + student.isScienceMajor);
System.out.println("gender? " + student.gender);
}
}
25
28
Reference Data Fields



The data fields can be of reference types
For example, the following Student class contains a data
field name of the String type
String is a REFERENCE TYPE as well (it is a class)
public class Student {
String name; // name has default value null
int age; // age has default value 0
boolean isScienceMajor; // isScienceMajor has default value false
char gender; //gender has default value (char)0
}
Warning!

Java assigns no default value to a local variable inside
a method
public class Test {
public static void main(String[] args) {
int x; // x has no default value
String y; // y has no default value
System.out.println("x is " + x);
System.out.println("y is " + y);
}
}
Compilation error: variables not
initialized
26
29
Default Value for a Data Field

The default value of a data fields:




null for a reference type
0 for a numeric type
false for a boolean type
(char)0 for a char type
Bank account example

State (property) of bank account



Behaviour of bank account




27
current balance
…
deposit money
withdraw money
get balance
…
Define and implement BankAccount class

Instance fields

Constructors initialize instance fields
Methods may nor may not change the instance fields, and
may or may not return an output value





Lab Today

balance
withdraw()
deposit()
getBalance()
Test the Class – BankAccountTester
Outline


Creating and testing a Square class
Create a test class: a class with a main method that
contains statements to test another class.
1.
2.
3.
Construct one or more objects of the class that is being
tested
Invoke one or more methods
Print out one or more results
Review

Concepts of objects and classes
Defining a class

Creating objects from a class



Today




BankAccount.java
BankAccountTester.java
Review

When you run the BankAccountTester program,
how many objects of class BankAccount are
constructed? How many objects of type
BankAccountTester?
Data fields, constructors, methods

Categories of variables
Using existing classes from Java API
Static variables and methods
Access modifiers
Using objects in methods and arrays
Categories of Variables

Instance fields



Local variables



Instance fields belong to an object
E.g. radius in Circle1
Local variables belongs to a method
E.g. area in Circle1.getArea() method
Parameter variables


Parameter variables belong to a method
E.g. newRadius in Circle1 constructor
Implicit and Explicit Parameters
Explicit parameter: defined in the method
definition



Created upon method call, initialized with the values
supplied
Implicit parameter: the object on which the
method is invoked



The this reference denotes the implicit parameter
Created upon method call, initialized to the object on
which the method is invoked
Use of an instance field name in a method denotes the
instance field of the implicit parameter
Using this

Use this explicitly when there is ambiguity
public class ThisTest {
private int number;
public void setNumber(int number){
number = number;
}
}
public class ThisTest {
private int number;
public void setNumber(int number){
this.number = number;
}
}
40
this - continued
Categories of Variables
Lifetime
Initialization
Instance
variables
Created when object is constructed and
die when object terminates
Initialized with default value or explicitly
Local
variables
Created when method is invoked and
die when method exits
Must be initialized explicitly
public class ThisTest1 {
private int number;
ThisTest1(int n) {
number = n;
}
ThisTest1() {
this(1);
}
}
Parameter
variables
Implicit parameter: the object the
method is invoked on
Explicit parameter: the value supplied
in the method call
41
this Keyword
Programming with Objects and Classes

The this reference denotes the implicit parameter


Compiler implicitly use this to reference the instance
variables of the object on which the method is invoked

double getArea() {
double area = radius * radius * Math.PI;
// double area = this.radius * this.radius * Math.PI;
return area;
}
Circle myCircle = new Circle(10.0);
double area = myCircle.getArea();
Defining and testing classes by creating objects
Using existing classes in Java API library

Check API for the usage – required parameters and return
values
Getting Input Using Scanner Class
0. Import Scanner class
The Random Class

import java.util.Scanner;

1. Create a Scanner object
Math.random() : a random double value between 0.0 and
1.0 (excluding 1.0).
A more useful random number generator is provided in
the java.util.Random class.
Scanner scanner = new Scanner(System.in);
2. Use methods next(), nextByte(), nextShort(), nextInt(), nextLong(),
java.util.Random
+Random()
Constructs a Random object with the current time as its seed.
+Random(seed: long)
Constructs a Random object with a specified seed.
nextFloat(), nextDouble(), or nextBoolean() to obtain a string, byte, short, int,
+nextInt(): int
Returns a random int value.
long, float, double, or boolean value.
+nextInt(n: int): int
Returns a random int value between 0 and n (exclusive).
+nextLong(): long
Returns a random long value.
+nextDouble(): double
Returns a random double value between 0.0 and 1.0 (exclusive).
+nextFloat(): float
Returns a random float value between 0.0F and 1.0F (exclusive).
+nextBoolean(): boolean
Returns a random boolean value.
System.out.print("Enter a double value: ");
Scanner scanner = new Scanner(System.in);
double d = scanner.nextDouble();
46
The Random Class Example
The Date Class

Use Date class to create an instance for the current date
and time and use its toString method to return the date
and time as a string.
The + sign indicates
public modifer
Random random = new Random(3);
System.out.print("From random1: ");
for (int i = 0; i < 10; i++) {
System.out.print(random.nextInt(1000) + " ");
}
java.util.Date
+Date()
Constructs a Date object for the current time.
+Date(elapseTime: long)
Constructs a Date object for a given time in
milliseconds elapsed since January 1, 1970, GMT.
+toString(): String
Returns a string representing the date and time.
+getTime(): long
Returns the number of milliseconds since January 1,
1970, GMT.
+setTime(elapseTime: long): void
Sets a new elapse time in the object.
44
47
The Date Class Example
For example, the following code
Displaying GUI Components

GUI programs use Java classes such as JFrame, JButton,
JRadioButton, JComboBox, and JList to create frames,
buttons, radio buttons, combo boxes, lists, and so on

TestFrame.java
GUIComponents.java
import java.util.Date;
Date date = new Date();
System.out.println(date.toString());

displays a string like Sun Mar 09 13:50:19 EST 2003.
45
48
Instance Variables, and Methods


Instance variables belong to a specific instance
Instance methods are invoked by an instance of the
class
Using Instance and Class Variables and
Method

Add a class variable numberOfObjects (static variable
numberOfObjects) to track the number of Circle objects
created so far

Circle2.java
TestCircle2.java

49
52
Static Variables, Constants, and Methods
Caution

Static variables are shared by all the instances of
the class

Static constants are final variables shared by all the
instances of the class
Can we do the following ?

Static methods are not tied to a specific object
All the methods we used in Math are static methods, which are
defined using the static keyword.
double power = Math.pow(3, 2.5);
double area = Circle1.getArea()
getArea() is non-static. It must be invoked from an object:
Circle1 circle = new Circle1(10);
double area = circle.getArea();
50
53
Static Variable, constant, methods
Visibility Modifiers
 To

declare static variables, constants, and
methods, use the static modifier
static int numberOfCircles;
access static variables, constants, and
methods, use the class name

public
The class, data, or method is visible to any class in any
package.
 To
Math.PI
By default, the class, variable, or method can be
accessed by any class in the same package.

private
The data or methods can be accessed only by the declaring
class.
Math.random();
54
Accessor/Mutator Methods




Data Fields Should Be always private
Accessor methods

Only access the data fields without modifying them
E.g. getArea() of Circle1

To protect data and to make the class easy to maintain
Provide accessor and mutator methods for accessing and
modifying the fields - conventions: getX(), setX()
Mutator methods


Modify data fields
E.g. scale() of Square
class Thermometer {
private int temperature;
public void setTemperature(int temp) {
temperature = temp;
}
Setter
public void getTemperature() {
return temperature;
}
Getter
}
58
Visibility Modifiers and
Accessor/Mutator Methods
package p1;
public class C1 {
public int x;
int y;
private int z;
public void m1() {
}
void m2() {
}
private void m3() {
}
}
public class C2 {
void aMethod() {
C1 o = new C1();
can access o.x;
can access o.y;
cannot access o.z;
public class C3 {
void aMethod() {
C1 o = new C1();
can access o.x;
cannot access o.y;
cannot access o.z;
can invoke o.m1();
can invoke o.m2();
cannot invoke o.m3();
can invoke o.m1();
cannot invoke o.m2();
cannot invoke o.m3();
}
Billy
I don’t need any field
encapsulation. If you
want to change
temperature, use:
t.temperature = 10;
The thermometer does
not work for less than
5 degrees. We need to
disable the scale when
temperature is set
below 5 degrees…
}
}
}
package p1;
class C1 {
...
}
Encapsulation Comic Book
package p2;
I will use field
encapsulation. If you
want to change the
temperature, use:
t.setTemperature(10);
package p2;
public class C2 {
can access C1
}
public class C3 {
cannot access C1;
can access C2;
}
Jamie
OK boss…
public void
setTemperature(int t) {
if (t < 5) {
//disable scale
} else {
this.temperature = t;
}
59
56
NOTE
Example of Data Field Encapsulation
Circle
The - sign indicates
private modifier
public class Foo {
private boolean x;
public static void main(String[] args) {
Foo foo = new Foo();
System.out.println(foo.x);
System.out.println(foo.convert());
}
public class Test {
public static void main(String[] args) {
Foo foo = new Foo();
System.out.println(foo.x);
System.out.println(foo.convert(foo.x));
}
}
private int convert(boolean b) {
return x ? 1 : -1;
}
-radius: double
The radius of this circle (default: 1.0).
-numberOfObjects: int
The number of circle objects created.
+Circle()
Constructs a default circle object.
+Circle(radius: double)
Constructs a circle object with the specified radius.
+getRadius(): double
Returns the radius of this circle.
+setRadius(radius: double): void
Sets a new radius for this circle.
+getNumberOfObject(): int
Returns the number of circle objects created.
+getArea(): double
Returns the area of this circle.
}
(a) This is OK because object foo is used inside the Foo class
(b) This is wrong because x and convert are private in Foo.
Circle3.java
57
60
Passing Objects to Methods



Array of Objects, cont.
Passing by value for primitive type value (the value is
passed to the parameter)
Passing by value for reference type value (the value is the
reference to the object)
Circle[] circleArray = new Circle[10];
TestPassObject.java
61
64
Passing Objects to Methods, cont.
Array of Objects, cont.

Summarize the areas of the circles

TotalArea.java
62
65
Array of Objects
Practice problems
Circle[] circleArray = new Circle[10];




An array of objects is actually an array of reference
variables
Invoking circleArray[1].getArea() involves two levels of
referencing
circleArray references to the entire array
circleArray[1] references to a Circle object.

Basic concept of objects and classes

Static variables and methods

Visibility modifiers, accessor and mutator methods

Using Objects in Arrays and methods




63
7.5
7.10, 7.12
7.15
7.17, 7.20