java i lecture_9_upd1

147
Java I—Copyright © 2000 Tom Hunter

Upload: manglam-jaiswal

Post on 26-May-2015

89 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Page 2: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Chapter 8

Object-Based Programming

Page 3: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

• How did companies like Dell, Compaq and Gateway get so big?

• They bought components from other companies and assembled the pieces into their products.

The Genius of Using Objects

Page 4: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

• Dell didn’t design its own motherboards.

• Compaq didn’t engineer its own hard drives or operating systems.

• They bought the pieces and let somebody else do the engineering.

The Genius of Using Objects

Page 5: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

• Dell, Compaq and Gateway let somebody else reinvent the power supply or the motherboard.

• Object-Oriented programming is the same idea.

• A program is composed of generic objects, with certain standard properties, and certain standard operations the objects can perform.

The Genius of Using Objects

Page 6: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

• Dell doesn’t care how the power supply works.

• Dell cares if the power supply works.

• How the power supply works is hidden and private.

• Only the end result is visible.

The Genius of Using Objects

Page 7: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

• Dell is only exposed to the end result.

• Most important is the power supply’s public face—the power.

• Dell doesn’t care how it works internally.

The Genius of Using Objects

Page 8: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

• Likewise, in OOP, you only care about what the objects expose.

• You can’t know how somebody else’s object works.

The Genius of Using Objects

Page 9: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

• You don’t care how the JOptionPane works.

• You care about its public methods—its “interface”.

You only care about its public methods !

The Genius of Using Objects

Page 10: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

• In traditional procedural programming, you search for verbs in the problem definition.

• In procedural programming, the verbs directly suggest procedures and then, lastly, you think of data variables to go with those procedures.

The Genius of Using Objects

Page 11: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

• In OOP, you put data structures first, and then look at the algorithms that operate on the data.

The Genius of Using Objects

Page 12: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

• The secret to effective OOP:

Each object carries out a small set of related tasks.

If an object needs a task done—but that task isn’t the job of that object—then that object asks another object to do the task.

The Genius of Using Objects

“If I can’t do it, then I’ll

ask somebody who can.”

Page 13: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

• Again, since the first object can’t do the task, it asks the second object to carry out the task.

• In OOP jargon, we say:

The Genius of Using Objects

“A Client object sends a message to a Server object.”

Page 14: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

• In OOP, one object must never directly manipulate the internal data of another object.

• Rather, all communication is through “messages”.

(A message is another name for a method call.)

The Genius of Using Objects

encapsulation

Page 15: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

• When you design your object to hide how it handles requests...

(messages / method calls)

...you make it easily reusable.

The Genius of Using Objects

Page 16: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

• When you see a Windows OS computer lock up, and you do a CTRL-ALT-DEL, the “Close Program” window that pops up might say:

(Not Responding)

• That message means that some Windows object is not responding to messages.

• Some program called a method, but Windows failed to respond. (No surprise)

The Genius of Using Objects

Page 17: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Class

OOP Vocabulary

Page 18: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

class• The term class is the blueprint or recipe from which the object is actually made, or “instantiated.”

MyClass boop;

boop = new MyClass();

We are now familiar with this: The first “MyClass boop; ” makes a reference called “boop.”

OOP Vocabulary

Page 19: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

MyClass boop;

At this point, the reference called “boop” does not actually point to any existing object.

Soon, it will point to an object of type MyClass, but now the object doesn’t exist.

OOP Vocabulary

Page 20: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

MyClass boop = new MyClass();

When this statement executes, the new keyword executes the default Constructor for MyClass, which actually creates an object in memory and assigns that reference to boop.

The handle to that just-created object is given to the MyClass reference boop.

Now boop points to the new MyClass object.

OOP Vocabulary

Page 21: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

state

behavior

identity

Page 22: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

state

behavior

identity

• Each object in OOP has three key characteristics:

What?

How?

Who?

OOP Vocabulary

Page 23: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

state behavior identity

• Key characteristics:

(What) What is the object’s state?

(How) What is the object’s behavior?

(Who) What is the object’s identity?

OOP Vocabulary

Page 24: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

state behavior identity

• All instances of a class have the same instance variables, but of course those variables have different values inside them.

• The state—or current values—for an instance of a class, is called the “state” of that class.

• The current values of those variables define the current situation or state of this instance of the class.

OOP Vocabulary

Page 25: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

state behavior identity

• For example, if I have a class called HourlyEmployee, then it contains instance variables:

first_name

last_name

soc_sec_number

hourly_rate

current_vacation_time

OOP Vocabulary

Page 26: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

state behavior identity

• All objects that are instances of the same class share the same behavior.

• They all have the same methods.

• We could send the same messages to all instances of the a class and all would understand and respond to the messages.

OOP Vocabulary

Page 27: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

state behavior identity • My class is: HourlyEmployee• All instances of this class have these methods: calculate_pay()

setName()getName()

setSSN()getSSN()

getVacationTime()setVacationTime()

getHourlyRate()setHourlyRate()

OOP Vocabulary

Page 28: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

state behavior identity • My class is: HourlyEmployee

• Every example, or instantiation, of this class has the same methods (behavior) available to it.

OOP Vocabulary

Page 29: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

state behavior identity • My class is: HourlyEmployee

• Let’s instantiate HourlyEmployee :

HourlyEmployee joseph; // empty reference.

joseph = new HourlyEmployee(‘Joe’,’Smith’,

’598-22-7893’,’$10.00’,’22.25’);

• Now, I have created an instance of the class HourlyEmployee.

OOP Vocabulary

Page 30: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

state behavior identity

• My class is: HourlyEmployee

• I have instantiated HourlyEmployee.

• My instance is called joseph.

• The identity of my instance is joseph.

OOP Vocabulary

Page 31: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

state behavior identity

• The identity of my instance is joseph.

• The state of my instance is:first_name = ‘Joe’last_name = ’Smith’soc_sec_number = ’598-22-7893’hourly_rate = ’$10.00’current_vacation_time = ’22.25’

• The behavior of my instance is:calculate_pay()setName()getName()setSSN()getSSN()

OOP Vocabulary

Page 32: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

state behavior identity• Now, I will instantiate three objects:

HourlyEmployee marie;marie = new HourlyEmployee(‘Mary’,’J.’,

’555-24-1516’,’$30.00’,’0’);

HourlyEmployee theodore;theodore = new HourlyEmployee(‘Ted’,’L.’,

’681-22-9875’,’$10.00’,’22’);

HourlyEmployee david;david = new HourlyEmployee(‘Dave’,’D.’,

’198-99-0098’,’$15.00’,’8’);

OOP Vocabulary Tell me the identity for each of the three.

Page 33: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

state behavior identity• Identity is the reference to this instantiation.

HourlyEmployee marie;marie = new HourlyEmployee(‘Mary’,’J.’,

’555-24-1516’,’$30.00’,’0’);

HourlyEmployee theodore;theodore = new HourlyEmployee(‘Ted’,’L.’,

’681-22-9875’,’$10.00’,’22’);

HourlyEmployee david;david = new HourlyEmployee(‘Dave’,’D.’,

’198-99-0098’,’$15.00’,’8’);

OOP Vocabulary

Page 34: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

state behavior identity

HourlyEmployee marie;marie = new HourlyEmployee(‘Mary’,’J.’,

’555-24-1516’,’$30.00’,’0’);

HourlyEmployee theodore;theodore = new HourlyEmployee(‘Ted’,’L.’,

’681-22-9875’,’$10.00’,’22’);

HourlyEmployee david;david = new HourlyEmployee(‘Dave’,’D.’,

’198-99-0098’,’$15.00’,’8’);

OOP Vocabulary Tell me the behaviors for each of the three.

Page 35: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

state behavior identity• All three have the exact same behaviors.

HourlyEmployee marie;marie = new HourlyEmployee(‘Mary’,’J.’,

’555-24-1516’,’$30.00’,’0’);

HourlyEmployee theodore;theodore = new HourlyEmployee(‘Ted’,’L.’,

’681-22-9875’,’$10.00’,’22’);

HourlyEmployee david;david = new HourlyEmployee(‘Dave’,’D.’,

’198-99-0098’,’$15.00’,’8’);

OOP Vocabulary

Page 36: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

state behavior identity

HourlyEmployee marie;marie = new HourlyEmployee(‘Mary’,’J.’,

’555-24-1516’,’$30.00’,’0’);

HourlyEmployee theodore;theodore = new HourlyEmployee(‘Ted’,’L.’,

’681-22-9875’,’$10.00’,’22’);

HourlyEmployee david;david = new HourlyEmployee(‘Dave’,’D.’,

’198-99-0098’,’$15.00’,’8’);

OOP Vocabulary Tell me the state for each of the three.

Page 37: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

state behavior identity• The state of each instance is defined by its instance variables.HourlyEmployee marie;marie = new HourlyEmployee(‘Mary’,’J.’,

’555-24-1516’,’$30.00’,’0’);

HourlyEmployee theodore;theodore = new HourlyEmployee(‘Ted’,’L.’,

’681-22-9875’,’$10.00’,’22’);

HourlyEmployee david;david = new HourlyEmployee(‘Dave’,’D.’,

’198-99-0098’,’$15.00’,’8’);

OOP Vocabulary

Page 38: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

state behavior identity• The state of an instance can only be changed by going through its methods or behaviors.

HourlyEmployee marie;marie = new HourlyEmployee(‘Mary’,’J.’,

’555-24-1516’,’$30.00’,’0’);

marie.setSSN( ‘444-33-1264’ );

OOP Vocabulary

Page 39: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Class Scope

Page 40: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Class Scope• A class’s Instance variables and methods have a thing called “class scope.”

• Within the class (within the scope of that class), class member variables are accessible by name.

• So, inside or outside of any method in that class, those instance variables can be reached from anywhere in the class.

OOP Vocabulary

Page 41: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Class Scope

• If a member variable has been (foolishly) declared public, then it can be accessed outside of the class by simply referencing as follows:

ClassName.primitive_variable

ClassName.Object_variable.

• Another instance of this class has access to the instance variables in any other instance of this class.• You can use the instance identifier or the class name if it is declared as a “static” variable.

OOP Vocabulary

Page 42: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Cosmic Base Class

Page 43: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Cosmic Base Class

• In Java, all classes are built on other classes.

• We say, that one class extends another class.

• Ultimately, all classes in Java stem from one central “Cosmic Base Class” called Object.

• Even if you didn’t use the word “extends” in your class definition, you were still always extending Object by default.

OOP Vocabulary

Page 44: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Base Class

• When you extend any “Base Class”, the new (derived) class has all the properties ( instance variables) and methods of its parent, or Base Class.

• You can choose to modify or keep any method of the parent, or you can create methods that only apply to the child or “inherited” class.

OOP Vocabulary

Page 45: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Inheritance

Page 46: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Inheritance

• The concept of extending a base class is called “Inheritance.”

• Inheritance is the second fundamental concept of Object-Oriented programming.

(Encapsulation is the first,

Polymorphism is the third)

OOP Vocabulary

Page 47: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Relationships Between Classes

• Classes can be related to each other in one of three alternative ways:

use

containment ( “has-a” )

inheritance ( “is-a” )

OOP Vocabulary

Page 48: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

• When one class sends messages to another class, we say it “uses” the class that receives its messages.

Use

OOP Vocabulary

Page 49: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

• When one class lives as an Instance Variable within another class, we say it is “Contained”, a “has-a” relationship.

Containment ( “has-a” )

OOP Vocabulary

Page 50: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

• When one class inherits from another class, we say it is an “is-a” relationship.

inheritance ( “is-a” )

OOP Vocabulary

Page 51: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Relationships Between Classes: use

• Imagine that we have a class Order.

• Class Order needs to use the class Account, in order to check for credit status.

OOP Vocabulary

Page 52: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Relationships Between Classes: use

• Generally, if a method of class Ordersends a message to an object of class Account, then Order uses Account.

• In other words, Order uses Account whenOrder calls methods of Account.

OOP Vocabulary

AccountOrder message

Page 53: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Relationships Between Classes: use

• Also, we say class Order uses class Account if:

• A method of Order :createsreceives orreturnsobjects of class Account .

OOP Vocabulary

Page 54: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Relationships Between Classes: use

• Design Tip:

Avoid the “use” relationship whenever you can. If you “use” somebody else’s class, then any changes to that class can break your class.

OOP Vocabulary

Page 55: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Relationships Between Classes: containment

• The “Containment” relationship(also known as the “Composition” relationship)is a special casespecial case of the “use” relationship.

• In a Containment / Composition relationship,at least one method of one class actually contains an object of another class.

OOP Vocabulary

Page 56: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Order

Relationships Between Classes: containment

( In the use relationship, it calls methods of another object.)

( In the containment relationship, it contains another object.)

OOP Vocabulary

AccountOrder message

Account

Page 57: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Relationships Between Classes: containment

• In a “has-a” relationship, a class becomes an instance variable for the class we are defining.

OOP Vocabulary

public class Order extends Object{

Account acct = new Account();

Page 58: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Relationships Between Classes: inheritance

• Inheritance means specialization.

• When we inherit from a class, we wish to keep nearly everything in the base class (Superclass).

• In inheritance, we seek to elaborate on what we receive from the Superclass.

OOP Vocabulary

Page 59: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Relationships Between Classes: inheritance

• We start with the class Order.

• Then, we wish to create a Subclass off of Order.

• Our Subclass is called RushOrder.

OOP Vocabulary

Page 60: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Relationships Between Classes: inheritance

• Class RushOrder has everything that Order has, but it:

-adds a few instance variables, maybe -adds a method or two and -overrides a method or two.

OOP Vocabulary

Page 61: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Relationships Between Classes

• These three relationships between classes form the foundation of Object-Oriented Design.

use

“has-a”

“is-a”

OOP Vocabulary

Page 62: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Techniques for

Using Objects

Page 63: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Techniques for Using Objects

• We have spent a lot of time emphasizing the difference between a reference and the object to which it refers.

JLabel howdy;howdy = new JLabel( “How Are Ya?” );

OOP Vocabulary

Page 64: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

howdy

“How are Ya?”

• We start off by declaring a reference “howdy” to an object of type JLabel.

JLabel howdy;

• Then, we instantiate the object by calling its constructor with the new keyword, and assign the handle to this instantiation to the reference we declared: “howdy”.

JLabel howdy = new JLabel( “How Are Ya?” );

Page 65: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

howdy

“How are Ya?”

• Okay, what happens when I do the following statement?JLabel hello; // A new reference

hello = howdy;

howdy = new JLabel( “How Are Ya?” );

hello

• Now, both references point to the exact same object.

• Any changes made from howdy will be reflected in hello.

Page 66: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

import javax.swing.*;public class JLabelAssign{

public static void main( String args[] ){

JLabel howdy, hello;String out1, out2;howdy = new JLabel( "Howdy pardner!" );hello = new JLabel( "Hello there!" );out1 = howdy.getText();out2 = hello.getText();System.out.println( "Before howdy = " + out1 );System.out.println( "Before hello = " + out2 );

howdy = hello;

out1 = howdy.getText();out2 = hello.getText();

System.out.println( "After howdy = " + out1 );System.out.println( "After hello = " + out2 );

howdy.setText( "Yippy Kai Yay!" );

out1 = howdy.getText();out2 = hello.getText();

System.out.println( ”After Change howdy = " + out1 );System.out.println( ”Don’t change hello = " + out2 );System.exit( 0 );

}}

Before howdy = Howdy pardner!Before hello = Hello there!After howdy = Hello there!After hello = Hello there!After change howdy = Yippy Kai Yay!Don’t change hello = Yippy Kai Yay!Press any key to continue . . .

Page 67: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Controlling Access

to Methods and Variables

Page 68: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Controlling Access to Methods: public

• public—this lets clients see the services (methods) theclass provides (which means view the interface.)

—The interface is the collective name for all thevarious methods that are available in the class.

—Methods should be public.

OOP Vocabulary

Page 69: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Controlling Access to Member Variables and Methods: public & private

• private—this is the default setting. —It hides implementation details.

— Private data members (variables) are only accessiblethrough the public interface (Accessor methods)using public methods.

—Only utility methods should be made private.Utility methods are used only within the class.

OOP Vocabulary

Page 70: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Controlling Access to Member: package

• package—if you don’t specify that a method or adata variable is either private or public, thenwhen you have automatically given it package access.

• If your program has only one class definition—thischange is transparent. It has zero effect.

H O W E V E R...

OOP Vocabulary

Page 71: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Controlling Access to Member: package

• if you don’t specify either public or private for any feature…

[ meaning class, method or variable ]

can be accessed by all methods in the same package!

OOP Vocabulary

Page 72: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Controlling Access to Member: package

• So, if you have the following field in your class:

public class MyClass{

int mySalary;… }… and your class is stored in java.util.*;

then any other method in any class that is also stored in this package can change this variable to anything it wants. No methods needed!

OOP Vocabulary

Page 73: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

What’s more, anybody can add their own class to any

package. And if they had written a method to exploit that variable with package

access, they could do anything they wanted!

Page 74: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Controlling Access to Member: package

• So, if your program uses many classes that are stored in the same package, they can directly access each other’s package-access methods and data variables.

• They only need to use the reference.variable to do so.

int minute; // minute declared without public// or private.

Time2.minute // Other members of its class can// directly access minute.

OOP Vocabulary

Page 75: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Creating a Package

• A package is a way to organize classes.

• Normally, you create a public class.

• If you don’t define your class as public, then it’s onlyaccessible to other classes in the same package.

OOP Vocabulary

Page 76: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Creating a Package: the process

• use the keyword package followed by the location.package com.sun.java;

• The package statement must be the first statement in your class file.

• Compile it in DOS using the -d option

javac -d Time2.java

OOP Vocabulary

Page 77: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Final Instance Variables

Page 78: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Final Instance Variables

• The principle of encapsulation is built around the idea of limiting access to variables.

• This “least privilege” concept can be expanded to include variables that should never be changed, or “Constants”.

• Since this value is a constant, the compiler could optimize by replacing references to that variable with its constant value.

• Then there is no need to look up its value when it is referenced.

OOP Vocabulary

Page 79: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Final Instance Variables

• If a variable is defined as being “final” then it must be initialized in the same statement.

• It can never again be changed.

• By custom, it should be declared as all upper case.

• Any internal words in the identifier should be separated by underscores.

OOP Vocabulary

Page 80: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Final Instance Variables

• If you try to change a variable that you earlier declared as being “final”, then the compiler will complain.

• Obviously, it is better to have the compiler complain, than to have your program crash in production.

• Whether or not a variable is final is independent of its access. I.e., it can be declared either public or private.

private final int NUMBER_OF_MONTHS = 12;final String FIRST_MONTH = “January”;

OOP Vocabulary

Page 81: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Final Methods

Page 82: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Final Methods

• When a method is declared to be final, Java knows that the method can never be overridden.

• A final method must be fully defined when it is declared.

OOP Vocabulary

Page 83: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Final Methods

• You cannot, for example, have an abstract final

method. N E V E R

• Since it is final, and can never be overridden by subclasses, the Java compiler can replace the call to the method with inline code if it wants.

OOP Vocabulary

Page 84: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Final Methods

• As for security, if you declare a method to be final, then you can be sure it isn’t overridden.

• For example, class Object has a method called getClass() that is declared final.

• No subclass can override this method and thereby return some other class type to hide its identity.

OOP Vocabulary

Page 85: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Final Classes

Page 86: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Final Classes

• A final class makes all of its methods final as well, since a final class cannot be extended.

• Examples of final classes are:

Integer, Long, Float and Double.

• None of these “wrapper” classes can be subclassed.

• String is another class that’s declared final .

OOP Vocabulary

Page 87: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Final Classes

• So, if you want to stop programmers from every making a subclass of a particular class, you can declare that class to be final.

OOP Vocabulary

Page 88: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Objects Passed By Reference

Page 89: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Objects Passed By Reference

• As we know the name or reference for an object represents a memory location where the object is stored.

• When an object is passed, only the reference is passed.

Object-Based Programming

Page 90: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Objects Passed By Reference

• That means, only the address of the object is passed.

• A copy is NOT made of the object.

• This will have interesting implications.

Object-Based Programming

Page 91: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Creating Our First

Class Object

Page 92: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Creating Our First Class Object

• Up until now, our classes have either been Applets or Applications.

• Now we create a class that is neither.

• This class cannot execute unless it is instantiated by either an Application or an Applet.

Object-Based Programming

Page 93: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Creating Our First Class Object

• First we create the class.

• Then we create another Applet/Applicationclass to test it.

Object-Based Programming

Page 94: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

import java.text.DecimalFormat;

public class Time1 extends Object { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59

public Time1() { setTime( 0, 0, 0 ); }

public void setTime( int h, int m, int s ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); second = ( ( s >= 0 && s < 60 ) ? s : 0 ); }

We would use this class to display the time, and control how the user changed it.

Page 95: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

import java.text.DecimalFormat;

public class Time1 extends Object { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59

public Time1() { setTime( 0, 0, 0 ); }

public void setTime( int h, int m, int s ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); second = ( ( s >= 0 && s < 60 ) ? s : 0 ); }

We can only have one public class per file.This class would be stored in a file called

“Time1.java.”Question: Does that mean we can include other classes in

our file—if they are not declared public?

Page 96: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

import java.text.DecimalFormat;

public class Time1 extends Object { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59

public Time1() { setTime( 0, 0, 0 ); }

public void setTime( int h, int m, int s ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); second = ( ( s >= 0 && s < 60 ) ? s : 0 ); }

In keeping with encapsulation, the member-access modifiers declare

our instance variables private.

When this class gets instantiated, the only way to access these

variables is through the methods of the class.

Page 97: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

import java.text.DecimalFormat;

public class Time1 extends Object { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59

public Time1() { setTime( 0, 0, 0 ); }

public void setTime( int h, int m, int s ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); second = ( ( s >= 0 && s < 60 ) ? s : 0 ); }

The Constructor method “ Time1()” must have the same name as the class so the compiler always knows how to initialize the class.

Page 98: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

import java.text.DecimalFormat;

public class Time1 extends Object { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59

public Time1() { setTime( 0, 0, 0 ); }

public void setTime( int h, int m, int s ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); second = ( ( s >= 0 && s < 60 ) ? s : 0 ); }

The method setTime()takes in the time arguments. It validates the hours, minutes and seconds to make sure they make sense. Now you can see why the concept of a class might be pretty nifty.

Page 99: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Different Kinds of Methods

Page 100: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

The different kinds of methods are…

Constructor—instantiates the class.

Accessor—accesses the member variables in the class.

Mutator—(also called Manipulator)—to change or write to the member variables of the class.

Utility—private methods that do work for the other methods of the class.

( More Later )

Page 101: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

public String toUniversalString() { DecimalFormat twoDigits = new DecimalFormat( "00" );

return twoDigits.format( hour ) + ":" + twoDigits.format( minute ) + ":" + twoDigits.format( second ); }

public String toString() { DecimalFormat twoDigits = new DecimalFormat( "00" ); return ( (hour == 12 || hour == 0) ? 12 : hour % 12 ) + ":" + twoDigits.format( minute ) + ":" + twoDigits.format( second ) + ( hour < 12 ? " AM" : " PM" ); }

} // end of class Time1

Method toString() originates in class Object. When you want to see what is in the instance variables of the class, you call the toString() method. Every class

you create should override this method and create its own copy.

Page 102: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Using Our New Class• Now we have a new class Time1.

• Class Time1 keeps time variables.

• The class also validates any time we wish to create.

• It prevents us from creating an impossible time.

Page 103: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Using Our New Class• As of yet, there is no actual object.

• Right now, it is only a recipe for an object of our type.

• In other words, we haven’t instantiated it yet.

Page 104: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Using Our New Class

• We cannot instantiate it in this class.

• We need to create another class to do actually make an example of this class.

Page 105: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Using Our New Class

• We need to create a driver program TimeTest.java

• The only purpose of this new class is to instantiate and test our new class Time1.

Page 106: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

import javax.swing.JOptionPane;

public class TimeTest{ public static void main( String args[] ) { Time1 t = new Time1(); // calls Time1 constructor

}}

• Now we are using the class Time1 that we just created.

• This line creates a reference “t” to an object of type Time1 .

• Then, the “new Time1() calls the Constructor method to instantiate our new Time1 object “t”.

Page 107: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

import javax.swing.JOptionPane;

public class TimeTest{ public static void main( String args[] ) { Time1 t = new Time1(); // calls Time1 constructor String output;

output = "The initial universal time is: " + t.toUniversalString() + "\nThe initial time is: " + t.toString() + "\nImplicit toString() call: " + t;

System.exit( 0 ); }}

• In this next line, you see how we are calling two different methods of our new class. We’re calling toUniversalString() andtoString().

Page 108: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

import javax.swing.JOptionPane;

public class TimeTest{ public static void main( String args[] ) { Time1 t = new Time1(); // calls Time1 constructor String output;

output = "The initial universal time is: " + t.toUniversalString() + "\nThe initial time is: " + t.toString() + "\nImplicit toString() call: " + t;

System.exit( 0 ); }}

• One curious thing is this naked reference “ t ” sitting out here by itself. What does that do?

• Well, anytime you concatenate an object to a String, you automatically call its toString() method.

Page 109: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

import javax.swing.JOptionPane;

public class TimeTest{ public static void main( String args[] ) { Time1 t = new Time1(); // calls Time1 constructor String output;

output = "The initial universal time is: " + t.toUniversalString() + "\nThe initial time is: " + t.toString() + "\nImplicit toString() call: " + t;

t.setTime( 13, 27, 6 ); output += "\n\nUniversal time after setTime is: " + t.toUniversalString() + "\nStandard time after setTime is: " + t.toString();

t.setTime( 99, 99, 99 ); // all invalid values output += "\n\nAfter attempting invalid settings: " + "\nUniversal time: " + t.toUniversalString() + "\nStandard time: " + t.toString();

JOptionPane.showMessageDialog( null, output, Testing Class Time1", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); }}

Page 110: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Varieties of Methods: details• In the Applications we have created so far, there has only been one method—main.

• In the Applets we have created, there have been several standard methods:

init(),

start() and

paint().

• Applets have other standard methods, as we know.

Page 111: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Varieties of Methods: details

• The class we created—Time1—is neither an Application nor an Applet.

• Time1 cannot execute unless another program first instantiatesinstantiates it.

Page 112: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Varieties of Methods

• Encapsulating data and the methods used to access that data is the central role of the class in Object Oriented Programming.

• With this class, we make the member variables private.

• We create methods used to access the member variables.

Page 113: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Varieties of Methods

• There are several different varieties of methods, and each kind has a different sort of job to do.

Constructors—public methods used to initialize a class.

Accessors—public methods ( gets ) used to read data.

Mutators—public methods ( sets ) used to change data.

Utility—private methods used to serve the needs of other public methods.

Finalizers—protected methods used to do termination housekeeping.

Page 114: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Varieties of Methods: Constructors

• The Constructor is named exactly the same as the class.

• The Constructor is called when the new keyword is used.

• The Constructor cannot have any return type—not even void.

Page 115: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Varieties of Methods: Constructors

• The Constructor instantiates the object.

• It initializes instance variables to acceptable values.

• The “default” Constructor accepts no arguments.

• The Constructor method is usually overloaded.

Page 116: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Varieties of Methods: Constructors

• The overloaded Constructor usually takes arguments.

• That allows the class to be instantiated in a variety of ways.

• If the designer neglects to include a constructor, then the compiler creates a default constructor that takes no arguments.

• A default constructor will call the Constructor for the class this one extends.

Page 117: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

public Time2(){

setTime( 0, 0, 0 ); }

• This is the first Constructor.

• Notice that it takes no arguments, but it still sets the instance variables for hour, minute and second to consistent initial values of zero.

Page 118: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

public Time2(){

setTime( 0, 0, 0 ); }

public Time2( int h, int m, int s ) {

setTime( h, m, s ); }

• These are the first two Constructors.

• The second one overrides the first.

• The second Constructor takes arguments.

• It still calls the setTime() method so it can validate the data.

Page 119: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

public Time2(){

setTime( 0, 0, 0 ); }

public Time2( int h, int m, int s ) {

setTime( h, m, s ); }

public Time2( Time2 time ){ setTime( time.hour, time.minute, time.second );}

• This final constructor is quite interesting.

• It takes as an argument a Time2 object.

• This will make the two Time2 objects equal.

Usually, we can’t directly access the private instance variables of an object, because it violates encapsulation.

However, objects of the same class are permitted to access each other’s instance variables directly.

Page 120: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Varieties of Methods: Accessors

• Public method to display private variables.

• Access to private member variables is provided through the Accessor, or “get” methods.

• This allows the designer of the class to control how and anyone can access the private data.

• Also called Query methods.

Page 121: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Varieties of Methods: Mutators

• Public methods used to change private variables.

• Mutators “set” private data.

• The designer can filter he incoming data and ensure it is correct before it is used to change the private data.

• This permits the data to be correctly validated before it is used to update the member variables.

• Also called Manipulator methods

Page 122: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

The this Reference

Page 123: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

The this Reference• You were sitting in your Ferrarri in your driveway.

• Next door, your plumber neighbor was sitting in her Ferrarri.

• If you wanted to refer to your neighbor’s Ferrarri, you would naturally say “Jane’s Ferrarri….”

• Likewise, it would be perfectly natural for you to refer to the car you were sitting in as “this Ferrarri….”

Page 124: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

The this Reference

• “this Ferrarri….”

• In Java, the this reference is used to refer to the object you are inside of at this moment.

• We say that each object has a reference to itself—called the this reference.

Page 125: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

The this Reference

• The this reference is used to refer to both the instance variables and methods of an object.

• In Event Handlers, we have used the this reference to show that this Applet (and by implication this Applet’s actionPerformed method) will listen for events from this object.

• The this reference can also be used for cascading method calls which allow a reference to be passed back up the calling chain.

Page 126: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Finalizer Methods

Page 127: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Finalizer Methods• We know that the Constructor method is used to instantiate and initialize an object in memory.

• To avoid the problem called a “memory leak”—one which plagues the C/C++ environment—it is beneficial to have an anti-Constructor method.

• Such methods exist. They are called Finalizers, and they control the orderly removal of objects from memory.

Page 128: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Finalizer Methods

• When an object has gone out of scope, the finalizer executes automatically to clean up ( release ) used system resources.

• When there are no longer any references to an object, it is eligible for garbage collection.

• Garbage Collection is done automatically to return RAM memory back to the system—so called “termination housekeeping.”

Page 129: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Finalizer Methods• We say that an unused object is marked for garbage collection.

• A finalizer method must always be called finalize()

• It always takes no arguments and returns void.

• The finalize() method is one of the 11 methods inherited from method Object.

Page 130: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Static Class Members

Page 131: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Static Class Members• When we instantiate a class, each instantiation of that class gets its own private copies of the instance variables for that class.

• However, in certain cases, we would like to have all the instances of the class share one copy of a variable, instead of each having their own copy.

interestRate

Page 132: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Static Class Members

• Say we had 30,000 instances of a class called SavingsAccount.

• If we changed the interestRate variable they all contained, we would have to make 30,000 method calls to make the change in all of them.

Page 133: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Static Class Members

• However, if we just had defined the interest variable as static, we would have only a single copy that all of them shared.

static interestRate

• Only the members of the class could access the static variable.

• Instance variables that are defined as being static have class scope.

Page 134: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Static Class Members

• If you define your static instance variables as public:

public int static interestRate

then this variable can be reached by a reference to any object of that class, or through the class name using the dot operator:

savacct.interestRate or

SavingsAccount.interestRate

Or

ClassName.staticFieldName;

Page 135: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Static Class Members

• If you define your static instance variables as private:

private int static interestRate

then the private static instance variables can only be accessed through methods of the class, like any other private variable.

Page 136: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Static Class Members

• Static class members can be accessed even when no instances of that class exist:

—To access a public static class member when the class is not instantiated, you tack the name of the class to the name of the variable:

SavingsAccount.interestRate

Math.PI is a static member variable

Page 137: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Static Class Members

—To access a private static class member when the class is not instantiated, you still prefix with the class name, but then you also use a public static method:

SavingsAccount.getInterestRate()

Page 138: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

public class Employee extends Object{ private String firstName; private String lastName; private static int count; // # of objects in memory

public Employee( String fName, String lName ) { firstName = fName; lastName = lName; ++count; // increment static count of employees System.out.println( "Employee object constructor: " + firstName + " " + lastName ); }

protected void finalize() { —count; // decrement static count of employees System.out.println( "Employee object finalizer: " + firstName + " " + lastName + "; count = " + count ); }

public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public static int getCount() { return count; } }

Because count is declared as private static, the only way to access its data is

by using a public static method.

Page 139: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

public class Employee extends Object{ private String firstName; private String lastName; private static int count; // # of objects in memory

public Employee( String fName, String lName ) { firstName = fName; lastName = lName; ++count; // increment static count of employees System.out.println( "Employee object constructor: " + firstName + " " + lastName ); }

protected void finalize() { —count; // decrement static count of employees System.out.println( "Employee object finalizer: " + firstName + " " + lastName + "; count = " + count ); }

public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public static int getCount() { return count; } }

Page 140: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Static Class Members

—When even a single instance of the class SavingsAccount exists ( is instantiated ), then any of those existing classes can access our static variable ( interestRate) simply by using its name:

interestRate

Page 141: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Static Class Members

—When no objects of class SavingsAccount exist, our static variable can still be referenced, but only by going through the Class name and a public static method:

SavingsAccount.getInterestRate()

Page 142: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Static Class Methods

Page 143: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Static Class Methods• Just like static class members (data variables), static class methods belong to the class—not any one instantiation of the class.

• Static class methods do not operate on any instance of a class.

• That means you can use them without creating any instance of a class.

• For example, all the methods built into the Math class are static methods.

Page 144: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Static Class Methods

• You use this general syntax when using Static Class Methods:

ClassName.staticMethod( parameters );

Page 145: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Static Class Methods

I M P O R T A N T• Because static methods do not work with an instance of a class, they can only access static fields.

• Let’s think about this:—No instance of the class is instantiated.

—In this situation, the only thing that could possibly be present is a static member.

—Thus, the only thing that would be around for a static method to see is another static member.

Page 146: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Static Class Methods

• Finally, consider the most famous of all static methods:

public static void main( String args[] )

• Since main is static, you don’t need to create an instance of the class in order to call it—and the Java interpreter doesn’t either.

Page 147: Java i lecture_9_upd1

Java I—Copyright © 2000 Tom Hunter

Static Class Methods

• Once again, “static” means:

variables andmethods

that belong to a class but not to any particular object of the class.