objects and classes chapter 6 csci 1302. csci 1302 – objects and classes2 outline introduction...

37
Objects and Classes Chapter 6 CSCI 1302

Upload: george-turner

Post on 02-Jan-2016

282 views

Category:

Documents


1 download

TRANSCRIPT

Objects and Classes

Chapter 6CSCI 1302

CSCI 1302 – Objects and Classes 2

Outline

• Introduction• Defining Classes for Objects• Constructing Objects• Accessing Objects

– Reference Variables and Types– Accessing an Object’s Data and Methods– The null Value– Differences Between Primitive and

Reference Variable Types

CSCI 1302 – Objects and Classes 3

Outline

• Using Classes from the Java Library• Visibility Modifiers, Accessors, and

Mutators• Data Field Encapsulation• Immutable Objects and Classes• Passing Objects to Methods• Static Variables, Constants, and

Methods

CSCI 1302 – Objects and Classes 4

Outline

• The this keyword• Array of Objects• Class Abstraction and Encapsulation• Inner Classes• Case Study: StackofIntegers

CSCI 1302 – Objects and Classes 5

Introduction

• Procedural programming – data and operations are separate

• Object-oriented programming (OOP) – groups data and operations into a single entity

• Improves reusability, development, and maintenance

CSCI 1302 – Objects and Classes 6

Defining Classes for Objects

• An object represents a real-world entity• Has a unique identity, state, and

behaviors• State consists of data fields (properties)• Behavior is defined by a set of methods• State defines the object, behavior

defines what it does

CSCI 1302 – Objects and Classes 7

Defining Classes for Objects

data field 1

method n

data field m

method 1

(A) A generic object

...

...

State (Properties)

Behavior

radius = 5

findArea()

Data field, State

Properties

Method, Behavior

(B) An example of circle object

CSCI 1302 – Objects and Classes 8

Defining Classes for Objects

• Constructs that define objects of the same type

• Java classes use variables to define data fields and methods to define behaviors

• Also provide constructors used to create objects from the class

CSCI 1302 – Objects and Classes 9

Defining Classes for Objects 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 findArea() { return radius * radius * 3.14159; }

}

CSCI 1302 – Objects and Classes 10

Defining Classes for Objects 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 findArea() { return radius * radius * 3.14159; }

}

Data field

Method

Constructors

CSCI 1302 – Objects and Classes 11

Constructing Objects

Circle() {}

Circle(double newRadius) {radius = newRadius;

}

Constructors with no parameters are referred to as no-arg constructors.

CSCI 1302 – Objects and Classes 12

Constructing Objects

Constructors• Have the same name as the defining

class• Can be overloaded• No return type• Invoked using the new operator• If no constructor is explicitly declared, a

default no-arg constructor is created with an empty body

CSCI 1302 – Objects and Classes 13

Constructing Objects

ExamplesGeneral

new ClassName();

Specific new Circle();new Circle(5.0);

CSCI 1302 – Objects and Classes 14

Constructing Objects

circle1: Circle

radius = 2

new Circle()

circlen: Circle

radius = 5

new Circle()

...

UML Graphical notation for classes

UML Graphical notation for objects

Circle radius: double findArea(): double

UML Graphical notation for fields

UML Graphical notation for methods

CSCI 1302 – Objects and Classes 15

Accessing Objects

• Can be accessed through reference variables

ClassName objectRefVar;Circle myCircle;

• Class defines a reference typemyCircle = new Circle();

• One statementCircle myCircle = new Circle();

• An object created without a reference is an anonymous object

CSCI 1302 – Objects and Classes 16

Accessing Objects

Accessing Data and Methods• Can be accessed using dot notation

objectRefVar.data;objectRefvar.method(arguments);

• Circle class:myCircle.radius;myCircle.findArea();

• See the code in Circle.java and TestCircle.java for examples

CSCI 1302 – Objects and Classes 17

The null value

• Default literal value for reference type variables

• Default values of data fields:

• No default values for local variables inside a method

Reference type null

Numeric type 0

boolean false

char ‘\u0000’

CSCI 1302 – Objects and Classes 18

Differences Between Variable Types

• Two main types of variables: Primitive and Reference

• Primitive– Value is of the primitive type– Assignment sets the real value, copies

contents

• Reference– Value is a reference to where an object

is located– Assignment sets reference

CSCI 1302 – Objects and Classes 19

Differences Between Variable Types

• Garbage collection reclaims previous c1 object automatically (can assign null to force collection) See code in TestVarTypes.java

1

c1: Circle

radius = 5

Primitive type assignment i = j

Before:

i

2 j

2

After:

i

2 j

Object type assignment c1 = c2

Before:

c1

c2

After:

c1

c2

c2: Circle

radius = 9

CSCI 1302 – Objects and Classes 20

Using Classes from the Java Library

• Classes from the Java Library will often be used when developing programs

• You have already done this:System.out.println(“Some text here”);

• See Example 2.4 (p. 61) for an example using System.currentTimeMillis();

• Promotes reuse of code• http://java.sun.com/j2se/1.5.0/docs/api/

CSCI 1302 – Objects and Classes 21

Using Classes from the Java Library

Example: java.util.Date• Provides a system-independent

encapsulation of date and time• Can be used to create an instance of

the current date and time, use its toString() method to print time out

• Format: Mon Aug 15 13:19:37 EDT 2005

• See TestDate.java and TestFrame.java

CSCI 1302 – Objects and Classes 22

Visibility Modifiers

• Java provides several modifiers to control access to data, methods, and classes– public – Accessible from any class– private – Accessible only from within its

own class– Package-private – used if public or private is not specified, accessible by any class in the same package

CSCI 1302 – Objects and Classes 23

Visibility Modifiers

• Only used for members of a class, not local variables inside methods

public class C1 { public int x; int y; private int z; public void m1() { } void m2() { } private void m3() { } }

public class C2 { C1 o = new C1(); can access o.x; can access o.y; cannot access o.z; can invoke o.m1(); can invoke o.m2(); cannot invoke o.m3(); }

package p1; package p2;

public class C3 { C1 o = new C1(); can access o.x; cannot access o.y; cannot access o.z; can invoke o.m1(); cannot invoke o.m2(); cannot invoke o.m3(); }

CSCI 1302 – Objects and Classes 24

Data Field Encapsulation

• Declare the field private• Use get (or accessor) methods to return

values of data fieldspublic returnType getProperty();public boolean isProperty();

• Use set (or mutator) methods to update data fields

public void setProperty(dataType property);

• See ExtendedCircle.java

CSCI 1302 – Objects and Classes 25

Immutable Objects and Classes

• An object, that once created, cannot be changed is an immutable object

• The class it is derived from is an immutable class

• A class with all private data fields and no mutator methods is not necessarily immutable (p. 227)

• See Chair.java for an example of a immutable class

CSCI 1302 – Objects and Classes 26

Passing Objects to Methods

• Objects can be passed to methods• Reference to the object is what is

actually passed• Java passes all arguments using pass-

by-value• See TestPassObject.java for a simple

example and TestPassObjectExtended.java for a more complex example

CSCI 1302 – Objects and Classes 27

Static Variables, Constants, and Methods

• Instance variables are tied to specific instances of a class

• Static variables are shared between all instances of a class

• Static methods can be called without creating an instance of a class

• Declared using static keyword• Class constants can be declared using

the final keyword

CSCI 1302 – Objects and Classes 28

Static Variables, Constants, and Methods

CircleWithStaticVariableAndMethod -radius: double -numberOfObjects: int +getRadius(): double +setRadius(radius: double): void +getNumberOfObjects(): int +findArea(): double

1 radius

circle1 -radius = 1 -numberOfObjects = 2

instantiate

Memory

2

5 radius

numberOfObjects

UML Notation: +: public variables or methods -: private variables or methods underline: static variables or methods

circle2 -radius = 5 -numberOfObjects = 2

CSCI 1302 – Objects and Classes 29

Scope of Variables

• Class variables have a scope of the entire class

• Methods and variables can be declared in any order in the class except when their value is based on other variables

• Local variables take precedence over class variables although it is bad form to reuse variable names in most cases

CSCI 1302 – Objects and Classes 30

The this keyword

• Used to refer to the invoking class• Used most often when parameter name

in a method matches a data field in a class

public void setRadius(double radius) { this.radius = radius;

}

• See ExtendedChair.java for example of constructor using this

• See TestChair.java

CSCI 1302 – Objects and Classes 31

Array of Objects

• Object arrays can be created the same way that primitive arrays are created

Circle[] circleArray = new Circle[10];

• To initialize the array, use a for loop similar to this one

for (int i = 0; i < circleArray.length; i++) {circleArray[i] = new Circle();

}

CSCI 1302 – Objects and Classes 32

Array of Objects

• Actually involves two levels of referencing

• circleArray is an array of reference variables

• See TestCircleArray.java

reference

Circle object 0 circleArray[0]

circleArray

circleArray[1]

circleArray[9]

Circle object 9

Circle object 1

CSCI 1302 – Objects and Classes 33

Class Abstraction and Encapsulation

• Class abstraction – Separation of class implementation from the use of a class

• Class contract – Collection of methods and fields that are accessible from outside the class, along with the description of their behavior

• Class encapsulation – Details of implementation are encapsulated and hidden from the user

CSCI 1302 – Objects and Classes 34

Inner Classes

• A class defined within the scope of another class (AKA nested class)

• Can reference the data and methods defined in the outer class

• Can be declared public, protected, or private

• Can be declared static with some restrictions on access to the outer class

CSCI 1302 – Objects and Classes 35

Inner Classes

• Objects for inner classes are often created in the outer class

• Can be created from outside classesNon-static:OuterClass.InnerClass innerObject = outerObject.new InnerClass();

Static:OuterClass.InnerClass innerObject = new OuterClass.InnerClass();

CSCI 1302 – Objects and Classes 36

Case Study: StackofIntegers

• Data structure that holds objects in a last-in first-out (LIFO) fashion

• Stack operations: pop(), push(), and peek()

• Array-based implementation • Stacks are used often in programming• Java provides a full featured version in java.util.Stack

CSCI 1302 – Objects and Classes 37

Case Study: StackofIntegers

StackOfIntegers

-elements: int[] -size: int +StackOfIntegers() +StackOfIntegers(capacity: int) +empty(): boolean +peek(): int +push(element: int): int +pop(): int +getSize(): int

. . .

. . .

[0]

[1]

size - 1

capacity - 1