Top Banner
Copyright © 2014 by John Wiley & Sons. All rights reserved. 1 Objects and Classes
101

Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Dec 13, 2015

Download

Documents

Deirdre French
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 1

Objects and Classes

Page 2: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 2

Chapter Goals

To understand the concepts of classes and objects To be able to call methods To implement classes and test programs To understand the difference between objects and object

references

Page 3: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 3

Objects as Models

A program can be thought of as a model of reality, with objects in the program representing physical objects.

Properties of objects:• State (information stored within the object)

• Behavior (operations that can be performed on the object)

Page 4: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 4

E.g. Student Information System

Object: student• State:

• studentID• name• transcript

• Behavior: • register for course• Find advisor• Order transcript

Object: professor• State:

• emplyeeid• name• department

• Behavior: • Teach course• Assign grades

Page 5: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 5

E.g. Airline Reservation System

Object: Flight• State:

• scheduledDate

• Behavior: • check if it has room• Add reservation• Cancel reservation

Object: Airport• State:

• code• name

• Behavior: • Set address

Page 6: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 6

Representing Objects Within a Program

In Java, the state of an object is stored in instance variables (or fields or attributes).

The behavior of an object is represented by instance methods.

Page 7: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 7

Instance Variables

Some instance variables will store a single value.

Others may store entire objects.

E.g. • Instance variables needed for a bank account:

• balance (double)

• Instance variables needed for a car:• engineIsOn (boolean)• fuelRemaining (double)

• Instance variables needed for a student:• advisor(Professor)

Page 8: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 8

Instance Methods

In Java, performing an operation on an object is done by calling one of the instance methods associated with the object.

An instance method may require arguments when it’s called, and it may return a value.

When asked to perform an operation on an object, an instance method can lookup and/or change the values stored in any of the object’s instance variables.

Page 9: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 9

Examples of Instance Methods E.g. Instance methods for bank accounts:• deposit:

• Adds an amount to balance.• Therefore change balance instance variable.

• withdraw:• Subtracts an amount from balance.• Therefore change balance instance variable.

• getBalance: • Returns value of balance.• Does NOT change balance instance variable. Only look up.

• close: • Stores zero into balance.• Therefore change balance instance variable.

Page 10: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 10

Classes

A class describes a set of objects with the same behavior.

Examples of classes:• Student• Account• Hotel

Page 11: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 11

Classes vs Objects

The terms ‘class’ and ‘object’ are definitely related to one another, but different. 

Class:• Blue print of objects• actual written piece of code which is used to define common

properties and behaviors of any given class. • Student class (variables = name, major, method=setMajor)

Object:• An actual instance of a class. • Every object must belong to a class. • E.g. A Student object s1 with name=sam, major=biology

A Student object s2 with name=kim, major=physics

Page 12: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 12

Declaring a Class

A class declaration contains declarations of instance variables and instance methods.

Most class declarations also contain declarations of constructors, whose job is to initialize objects.

Form of a class declaration:public class class-name { //variable-declarations //constructor-declarations //method-declarations}

The order of declarations usually doesn’t matter.

Page 13: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 13

Access Modifiers

The declaration of an instance variable, a constructor, or an instance method usually begins with an access modifier (public or private).

An access modifier determines whether that entity can be :• accessed by other classes (public) or • only within the class itself (private).

The most common arrangement:• instance variables private • constructors and instance methods public.

Page 14: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 14

Declaring Instance Variables In class body we declare instance variables

E.g.public class BankAccount{

private double balance; …

}

Instance variables are usually private.

The only access to balance will be through the instance methods in the BankAccount class.

The policy of making instance variables private is known as information hiding.

Access modifier = private

Page 15: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 15

Example

Page 16: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 16

Declaring Instance Methods

Parts of an instance method declaration:• Access modifier• Return type.

• If no value is returned, the return type is void.• Method name• Parameters

• (none , one or multiple separated by commas)• Body

Outline of the deposit method:

public void deposit(double amount) { //method body: code for depositing money

}

Access modifier Return type Method name Parameter type Parameter name

Page 17: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 17

Method Overloading

Methods can be overloaded.

i.e. A class can contains more than one method with the same name.

The overloaded methods must have :• different numbers of parameters or • some difference in the types of the parameters.

Overloading is best used for methods that perform essentially the same operation.

The advantage of overloading: Fewer method names to remember.

Page 18: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 18

Example

Page 19: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 19

Example of 3 overloaded methods add:

Public class Calculator{

public int add(int a, int b) { return a+b;}

public double add(double a, double b){

return a+b;}

pubic int add(int a, int b, int c){

return a+b+c;}

}

Page 20: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 20

Declaring Constructors When an object is created, its instance variables are initialized by

a constructor.

A constructor looks like an instance method But has no result type name is the same as the name of the class itself.

A constructor for the BankAccount class:

public BankAccount(double initialBalance) { balance = initialBalance;

}

A class may have more than one constructor (overloaded constructors possible).

Discuss: default constructor

Page 21: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 21

Example: Employee classpublic class Employee{

private String name;private int age;private double salary;

// This is the constructor of the class Employee public Employee(String empName){ name = empName; }

public void setAge(int empAge){ age = empAge; }

public double getSalary(){ return salary; }}

Employee.java

Page 22: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 22

Programming Question Implement a class BankAccount.java (save in lec02

folder)that contains following:• Attributes/instance variables:

• balance

• Constructors• no-argument constructor : sets balance to zero• One argument constructor: takes one parameter-initial balance. Set balance

to initial balance

• Instance methods: deposit, withdraw and getBalance. • deposit method:

– accept one parameter : amount deposited– Updates balance– Returns nothing

• withdraw method:– accept one parameter : amount withdrawn– Updates balance– Returns nothing

• getBalance method: – no parameters accepted– Returns current balance

Page 23: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 23

Answerpublic class BankAccount{

private double balance; //constructor: initialze balance to zero public BankAccount() { balance = 0.0; } //constructor: intialize balance to initial balance public BankAccount(double initialBalance) { balance = initialBalance; } public void deposit(double amount) { balance += amount; } public void withdraw(double amount) { balance -= amount; } public double getBalance() { return balance; }}

BankAccount.java

Page 24: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 24

Specifying the Public Interface of a Class

public constructors and methods of a class form the public interface of the class.

These are the operations that any programmer can use.

Page 25: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 25

Commenting the Public Interface – Documenting a Class

Provide documentation comments for: • every class• every method• every parameter variable• every return value

Page 26: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 26

Commenting the Public Interface –Documenting a Method Start the comment with a /**. End with */.

Here are some common pre-defined tags: @author [author name]

• identifies author(s) of a class or interface. @version [version]

• version info of a class or interface. @param [argument name] [argument description]

• describes an argument of method or constructor. @return [description of return]

• describes data returned by method (unnecessary for constructors and void methods).

@exception [exception thrown] [exception description] • describes exception thrown by method.

@throws [exception thrown] [exception description] • same as @exception.

Page 27: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 27

Example: Documented Employee class/** * This class models an Employee. * @author Rasanjalee Dissanayaka */ public class Employee{ private int age; private String name;

/** * constructor, initialize employee with given name * @param empName the name of the employee * @param empAge the age of the employee */ public Employee(String empName, int empAge){ name = empName; age = empAge; } /** * set the age of the employee * @param empAge the age of the employee */ public void setAge(int empAge){ age = empAge; } /** * returns the age of the employee * @return the age of the student */ public int getAge(){ return age; }}

Page 28: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 28

Commenting the Public Interface – Documenting a Class

Javadoc Compilation• To generate the html documentation, run Javadoc followed by

the list of source files, which the documentation is to be generated for, in the command prompt /terminal window

• E.g.

c:\MyWork> javadoc A.java B.java c:\OtherWork\*.java 

• Using DrJava:• ToolsJavdocJavadoc All documentsselect locationclick ok

Page 29: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 29

Page 30: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 30

Programming Question

Modify BankAccount class to include javadoc comments at class, method, parameter and return value levels.

Generate javadoc documentation for the file.

Page 31: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 31

AnswerBankAccount.java

Page 32: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 32

Page 33: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 33

Question

Change accessmodifier of deposit method to private. How does this change the generated javadoc API?

Page 34: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 34

Answer

That means deposit method is not part of the public interface of BankAccount class anymore.

So, it is not shown in javadoc API page

Page 35: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 35

Creating Objects

Once a class has been declared, it can be used to create objects (instances of the class).

Each object/instance will contain its own copy of the instance variables declared in the class.

A newly created object can be stored in a variable whose type matches the object’s class:

BankAccount acct;

Technically, acct will store a reference to an Account object, NOT the object itself.

Page 36: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 36

The new Keyword The keyword new placed before constructor call to create

object. new BankAccount(1000.00);

A newly created object can be stored in a variable (acct in this case):

BankAccont acct;acct = new BankAccount(1000.00);

The acct variable can be declared in the same statement that creates the BankAccount object:

BankAccount acct = new BankAccount(1000.00);

An object can also be created using the second constructor in the BankAccount class:

acct = new BankAccount();

Page 37: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 37

How Objects Are Stored

A variable of an primitive (non-object) type can be visualized as a box:

int i;

Assigning a value to the variable changes the value stored in the box:

i = 0;

Page 38: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 38

Object Variables An object variable, on the other hand, doesn’t actually

store an object. Instead, it will store a reference to an object.

An object variable can still be visualized as a box:BankAccount acct;

Suppose that a new object is stored into acct:

acct = new BankAccount(500.00);

reference

BankAccount object

Page 39: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 39

The null Keyword

To indicate that an object variable doesn’t currently point to an object, the variable can be assigned the value null:

acct = null;

When an object variable stores null, it’s illegal to use the variable to call an instance method.

If acct has the value null, executing the following statement will cause a run-time error (NullPointerException):

acct.deposit(500.00);

Page 40: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 40

Example1

Object with no reference to it

Object with reference e1 to it

Object reference e2 not referencing any object

Object reference e1 is now not referencing any object

Page 41: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 41

Example2

No errors when acct references a BankAccount object

Error occurs when acct DOES NOT references a BankAccount object

Page 42: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 42

How state of memory changes when you create objects

BankAccount harrysChecking;

Memory

harrysChecking

Page 43: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 43

How state of memory changes when you create objects

BankAccount harrysChecking;

harrysChecking = new BankAccount();Memory

harrysCheckingbalance=0.0

Page 44: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 44

How state of memory changes when you create objects

BankAccount harrysChecking;

harrysChecking = new BankAccount();

BankAccount momsSavings;

Memory

harrysCheckingbalance=0.0

momsSavings

Page 45: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 45

How state of memory changes when you create objects

BankAccount harrysChecking;

harrysChecking = new BankAccount();

BankAccount momsSavings;

momsSavings = new BankAccount(100.0);

Memory

harrysCheckingbalance=0.0

momsSavingsbalance=100.0

Page 46: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 46

Calling Instance Methods

Once an object has been created, operations can be performed on it by calling the instance methods in the object’s class.

Syntax of an instance method call:

objectName.

method-name( arguments ); E.g.

harrysChecking.deposit(1000.0);

The parentheses are mandatory, even if there are no arguments.

harrysChecking.getBalance();

Page 47: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 47

Page 48: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 48

Calling Instance Methods

Suppose that acct contains an instance of the BankAccount class.

Example calls of BankAccount instance methods:acct.deposit(1000.00); acct.withdraw(500.00); acct.getBalance();

An object MUST be specified when an instance method is called, because more than one instance of the class could exist:

acct1.deposit(1000.00);acct2.deposit(1000.00);

Page 49: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 49

Using the Value Returned by an Instance Method

When an instance method returns no result, a call of the method is an entire statement:

acct.deposit(1000.00);

When an instance method does return a result, that result can be used in a variety of ways.

1. One possibility is to store it in a variable:

double newBalance = acct.getBalance();

2. Another possibility is to print it:

System.out.println(acct.getBalance());

Page 50: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 50

Primitive variable Assignment If i has the value 10, assigning i to j gives j the

value 10 as well:

j = i;

Changing the value of i has no effect on j:

i = 20;

Assignment of objects doesn’t work the same way.

Page 51: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 51

Object Assignment

Assume that acct1 contains a reference to an BankAccount object with a balance of $500.

Assigning acct1 to acct2 causes acct2 to refer to the same object as acct1:

acct2 = acct1;

acct1 and acct2 are said to be aliases, because both represent the same object.

BankAccount object

Page 52: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 52

Object Assignment

If two BankAccount object variables reference same bank account object:

acct1 = acct2; Then the statement

acct1.deposit(500.00);will change the balance of acct2 to $1000.00:

Now both acct1.getBalance() and acct2.getBalance() will return 1000.0

BankAccount object

BankAccount object

Page 53: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 53

Example

Same memory address:i.e. both variables refer sameBankAccount object in the memory

Page 54: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 54

Programming Question

Implement a tester class BankAccountTester to test the functionality of BankAccount class. In the main method do following:1. create two BankAccount objects, harrysChecking and

momsSavings. harrysChecking should have $5000 at creation and momsSavings, $0.

2. Withdraw $500 from harrysChecking 3. Deposit $2000 to momsSavings4. Print current balance of both accounts

Sample output:

Page 55: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 55

Answer

public class BankAccountTester{ public static void main(String args[]) { BankAccount harrysChecking = new BankAccount(5000.0); BankAccount momsSavings = new BankAccount(); harrysChecking.withdraw(500.0); momsSavings.deposit(2000); double harrysBalance = harrysChecking.getBalance(); double momssBalance = momsSavings.getBalance(); System.out.println(" harrysChecking balance = "+ harrysBalance); System.out.println(" momsSavings balance = "+ momssBalance); }}

BankAccountTester.java

Page 56: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 56

Answer

public class BankAccountTester{ public static void main(String args[]) { BankAccount harrysChecking = new BankAccount(5000.0); BankAccount momsSavings = new BankAccount(); harrysChecking.withdraw(500.0); momsSavings.deposit(2000);

System.out.println(" harrysChecking balance = "+ harrsChecking.getBalance()); System.out.println(" momsSavings balance = "+ momsSavings.getBalance()); }}

Improved version

Page 57: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 57

Calling methods in same class

public class Calculator{

public int add(int a, int b){

return a+b;}

public double average(int a, int b){

int total = add(a,b);double avg = total/2.0;return avg;

}}

Page 58: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 58

Accessor and Mutator Methods

Accessor method: • does not change the internal data of the object on

which it is invoked.• E.g. getBalance method of BankAccount class

Mutator method: • changes the data of the object• E.g. withdraw and deposit methods of

BankAccount class

Page 59: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 59

Programming Question

1. Implement a class Rectangle that models a rectangle. Class has :• 4 instance variables: x(start x), y (start y), width, and height • 2 methods: getX () that reurn x value and translate(int dx, int dy)

that moves rectangle by dx pixels in x direction and by dy pixels in y direction

• One 4-arg constructor: initialize all four instance variables to values provided as parameters.

2. Write a RectangleTester class that create a rectangle, translate it by dx=5, dy =10 and print x value before and after translate is called.

Sample output:

Page 60: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 60

Answerpublic class Rectangle{ int x; int y; int width; int height; public Rectangle(int xval, int yval, int w, int h) { x = xval; y=yval; width = w; height = h; } public int getX() { return x; } public void translate(int dx, int dy) { x += dx; y += dy; }}

Rectangle.java

Page 61: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 61

public class RectangleTester{ public static void main(String args[]) { Rectangle rectangle = new Rectangle(5,10,20,25); System.out.println("x before: "+rectangle.getX()); rectangle.translate(25,25); System.out.println("x after: "+rectangle.getX()); }}

RectangleTester.java

Page 62: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 62

The this Reference

this is a reference variable denoting current object.

You can refer to any member of the current object from within an instance method or a constructor by using this.

E.g. balance = balance + amount;

actually meansthis.balance = this.balance +

amount;

When you refer to an instance variable in a method, the compiler automatically applies it to the this reference.

Page 63: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 63

The this Reference

Using this reference is not required.

Some programmers feel that inserting the this reference before every instance variable reference makes the code clearer:

public BankAccount(double initialBalance){ this.balance = initialBalance;}

Page 64: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 64

harrysChecking balance=0.01

2

3

4

State of memory

this

harrysChecking balance=0.0

momsSavings balance=5000.0

this

harrysChecking balance=0.0

this

momsSavings balance=5000.0

harrysChecking balance=0.0

momsSavings balance=6000.0

this

amount 1000.0

Page 65: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 65

Usage of this keyword1

this keyword can be used to:

1. refer current class instance variable2. invoke current class constructor.3. invoke current class method4. return the current class instance.5. pass as argument in the constructor call.6. pass as an argument in the method call.

Page 66: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 66

Using this with a Field1. Refer current class instance variable

Rectangle class with this keyword

Instance variable x

Parameter variable x

Page 67: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 67

The this Reference

The this reference can be used to distinguish between instance variables and local or parameter variables:

A local variable shadows an instance variable with the same name. • You can access the instance variable name through the this

reference.

Page 68: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 68

Programming Question

Using this with a Field: Modify BankAccount class to use this keyword to

refer to current instance variables

Page 69: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 69

Answer BankAccount.java

Page 70: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 70

Using this with a Constructor2. invoke current class constructor.

From within a constructor, you can this keyword to call another constructor in the same class.

If present, the invocation of another constructor must be the first line in the constructor.

Page 71: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 71

Programming Question

Using this with a constructor: Modify BankAccount class no argument constructor

so that it calls the one argument constructor to set the initial balance to 0.0.

public BankAccount()public BankAccount(double balance)

Page 72: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 72

Answer BankAccount.java

Page 73: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 73

Using this Reference for Method Calls

3. Invoke current class method

You may invoke the method of the current class by using the this keyword.

If you don't use the this keyword, compiler automatically adds this keyword while invoking the method.

Page 74: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 74

The this Reference for Method Calls

E.g.

Method call using this reference

Page 75: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 75

Ref: Java Programming: From the Beginning - KN King75

Garbage

Objects can become “orphaned” during program execution.

Consider the following example:BankAccount acct1= new BankAccount(100.0);BankAccount acct2= new BankAccount(200.0);acct1 = acct2;

After these assignments, the object that acct1 previously referred to is lost.

We say that it is garbage.

Page 76: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 76

Acct1 references the sameobject that acct2 references

Original object acct1 referenced now has no references pointing to it.So now it becomes a garbage object

Page 77: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 77

Garbage Object(i.e. no references to it)

BankAccount object

BankAccount object

Page 78: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 7878

Garbage Collection

Java provides automatic garbage collection: as a Java program runs, a software component known as the garbage collector watches for garbage and periodically “collects” it.

The recycled memory can be used for the creation of new objects.

Garbage collection normally takes place when the program isn’t doing any other useful activity.

Ref: Java Programming: From the Beginning - KN King

Page 79: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 79

Strings and Characters Characters:• A character is a value of the type char.

• Characters have numeric values

• Character literals are delimited by single quotes.

• E.g. char ch = ‘a’;

• Don't confuse them with strings • "H" is a string containing a single character.

Page 80: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 80

Unicode Characters

FROM: http://www.utf8-chartable.de/unicode-utf8-table.pl?utf8=dec

Page 81: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 81

String:• A string is a sequences of Unicode characters.• String is a class in java library• String is the only class whose instances can be created

without the word new:

String str1 = "abc";This is an example of magic. [IS IT ANYMORE?]

Page 82: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 82

Common String Methods: charAt

Each character in a string is identified by a position

Positions start with 0.

The String class has a large number of instance methods.

The charAt method returns a char value from a string

E.g.String name = "Harry”;char start = name.charAt(0); //set start value to ‘H’char last = name.charAt(4); //set last value t ‘y’

Page 83: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 83

Page 84: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 84

Example

Page 85: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 85

Common String Methods: indexOf

One version of the indexOf method searches for a string (the “search key”) within a larger string, starting at the beginning of the larger string.

Example: Locating the string "at" within str1:• Assume str1 = “Fat Cat”;

index = str1.indexOf("at");After this assignment, index will have the value 1.

If "at" had not been found anywhere in str1, indexOf would have returned –1.

Page 86: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 86

Example

Page 87: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 8787

Common String Methods: length The length method returns the number of

characters in a string.

E.gString name = "Harry”;int length = name.length(); //returns 5

Page 88: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 88

Common String Methods

toLowerCase and toUpperCase will convert the letters in a string to lowercase or uppercase.

Assume str1 = “Fat Cat”;

After the assignmentString str2 = str1.toLowerCase();the value of str2 is "fat cat".

After the assignmentString str2 = str1.toUpperCase();the value of str2 is "FAT CAT".

Characters other than letters aren’t changed by toLowerCase and toUpperCase.

Page 89: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 89

Only letters change

Original string s remains unchanged

Page 90: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 90

Common String Methods: trim

The trim method removes spaces (and other invisible characters) from both ends of a string.

After the assignmentsString str1 = " How now, brown

cow? ";String str2 = str1.trim();

the value of str2 will be"How now, brown cow?"

Page 91: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 91

Page 92: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 92

Common String Methods: Substrings Use the substring method to extract a part of a string.

The method call str.substring(start, pastEnd)• returns a string that is made up of the characters in the string str,

• starting at position start, and • containing all characters up to, but not including, the position pastEnd.

Example:String greeting = "Hello, World!”;String sub = greeting.substring(0, 5); // sub is "Hello”

Retrieve substring in index range 0-4; Index=5 is excluded

Page 93: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 9393

Chaining Calls of Instance Methods When an instance method returns an object, that

object can be used to call another instance method.

For example, the statementsstr2 = str1.trim();str2 = str2.toLowerCase();

can be combined into a single statement:str2 = str1.trim().toLowerCase();

Page 94: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 94

Programming Question

Write a tester class StringTester that test the use of String class. The program should first prompt the user for first name and store it in a appropriate variable. Then it should prompt the user again to enter his/her significant other’s first name and store it in a appropriate variable. Finally program will display the First Initials combined by & sign.

Following is sample run:

Enter your first name: RodolfoEnter your significant other's first name: SallyR&S

Page 95: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 95

Answer 1 import java.util.Scanner; 2 3 /** 4 This program prints a pair of initials. 5 */ 6 public class StringTester 7 { 8 public static void main(String[] args) 9 { 10 Scanner in = new Scanner(System.in); 11 12 // Get the names of the couple 13 14 System.out.print("Enter your first name: "); 15 String first = in.next(); 16 System.out.print("Enter your significant other’s first name: "); 17 String second = in.next(); 18 19 // Compute and display the inscription 20 21 String initials = first.substring(0, 1) + "&" + second.substring(0, 1); 23 System.out.println(initials); 24 } 25 }

StringTester.java

Page 96: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 96

Page 97: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 97

Programming Question

Modify StringTester class so that it include an input statement to read a name of the form “John Q. Public”.

Sample run is shown below:

Page 98: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 98

AnswerAnswer:

String first = in.next();String middle = in.next();String last = in.next();

Page 99: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 99

Wrapper classes

Found in java.lang package “Wrap" primitive values in an object

Primitive Type Wrapper Classbyte Byteint Integerdouble Doublefloat Floatlong Longshort Shortchar Characterboolean Boolean

Provide an assortment of utility functions• E.g. converting primitives to and from String objects,

Page 100: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 100

Integer class

Page 101: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Objects and Classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 101

References

Java Programming from the beginning, KN King