Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

80
Object-Oriented Java Object-Oriented Java Programming Programming INE2720 INE2720 Web Application Software Web Application Software Development Development Essential Materials Essential Materials

Transcript of Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

Page 1: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

Object-Oriented Java Object-Oriented Java ProgrammingProgramming

INE2720INE2720

Web Application Software Web Application Software DevelopmentDevelopment

Essential MaterialsEssential Materials

Page 2: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

22

Part A: Basic OOPart A: Basic OO

First Java Program – Welcome to First Java Program – Welcome to JavaJava

Object-oriented nomenclature Object-oriented nomenclature and conventionsand conventions

Instance variables (fields)Instance variables (fields) Methods (member functions)Methods (member functions) ConstructorsConstructors

Page 3: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

33

The First Java ProgramThe First Java Program

class Welcome {

/* The Welcome Program by J M Bishop Dec 96 ------------------- Illustrates a simple program displaying a message. */

public static void main (String [ ] args) { System.out.println("Welcome to Java!"); }}

Type all carefully and save it to a file named Welcome.java

Page 4: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

44

The First Java ProgramThe First Java Program

class Welcome {

/* The Welcome Program by J M Bishop Dec 96 ------------------- Illustrates a simple program displaying a message. */

public static void main (String [ ] args) { System.out.println("Welcome to Java!"); }}

Java program source files (.java) contain definition of classes

Page 5: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

55

The First Java ProgramThe First Java Program

class Welcome {

/* The Welcome Program by J M Bishop Dec 96 ------------------- Illustrates a simple program displaying a message. */

public static void main (String [ ] args) { System.out.println("Welcome to Java!"); }}

Curly braces pair enclose a block of code, class Welcome

here

Don’t miss me!

Page 6: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

66

The First Java ProgramThe First Java Program

class Welcome {

/* The Welcome Program by J M Bishop Dec 96 ------------------- Illustrates a simple program displaying a message. */

public static void main (String [ ] args) { System.out.println("Welcome to Java!"); }}

Curly braces pair enclose a block of code, method main()

here

Don’t miss me!

Page 7: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

77

The First Java ProgramThe First Java Program

class Welcome {

/* The Welcome Program by J M Bishop Dec 96 ------------------- Illustrates a simple program displaying a message. */

public static void main (String [ ] args) { System.out.println("Welcome to Java!"); }}

This is a block of comments, for human, not for computer

It explains to you what happens

Page 8: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

88

The First Java ProgramThe First Java Program

class Welcome {

/* The Welcome Program by J M Bishop Dec 96 ------------------- Illustrates a simple program displaying a message. */

public static void main (String [ ] args) { System.out.println("Welcome to Java!"); }}

/* and */ pair encloses a comment block

Don’t miss me!

Page 9: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

99

The First Java ProgramThe First Java Program

class Welcome {

/* The Welcome Program by J M Bishop Dec 96 ------------------- Illustrates a simple program displaying a message. */

public static void main (String [ ] args) { System.out.println("Welcome to Java!"); }}

This is a method of the class Welcome, named main()

Page 10: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1010

The First Java ProgramThe First Java Program

class Welcome {

/* The Welcome Program by J M Bishop Dec 96 ------------------- Illustrates a simple program displaying a message. */

public static void main (String [ ] args) { System.out.println("Welcome to Java!"); }}

There MUST be a pair of parentheses following ALL

method names

Don’t miss me!

Page 11: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1111

The First Java ProgramThe First Java Program

class Welcome {

/* The Welcome Program by J M Bishop Dec 96 ------------------- Illustrates a simple program displaying a message. */

public static void main (String [ ] args) { System.out.println("Welcome to Java!"); }}

A method may take some input from the caller, formally known

as arguments or parameters

Page 12: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1212

The First Java ProgramThe First Java Program

class Welcome {

/* The Welcome Program by J M Bishop Dec 96 ------------------- Illustrates a simple program displaying a message. */

public static void main (String [ ] args) { System.out.println("Welcome to Java!"); }}

A method may give some output to the caller too, known as return value

void means no return value

Page 13: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1313

The First Java ProgramThe First Java Program

class Welcome {

/* The Welcome Program by J M Bishop Dec 96 ------------------- Illustrates a simple program displaying a message. */

public static void main (String [ ] args) { System.out.println("Welcome to Java!"); }}

The static keyword before a method definition indicates this

is a class method

Page 14: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1414

The First Java ProgramThe First Java Program

class Welcome {

/* The Welcome Program by J M Bishop Dec 96 ------------------- Illustrates a simple program displaying a message. */

public static void main (String [ ] args) { System.out.println("Welcome to Java!"); }}

This method is a public one, others can call me.

Page 15: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1515

The First Java ProgramThe First Java Program

class Welcome {

/* The Welcome Program by J M Bishop Dec 96 ------------------- Illustrates a simple program displaying a message. */

public static void main (String [ ] args) { System.out.println("Welcome to Java!"); }}

Standard properties of the main() method

Page 16: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1616

The First Java ProgramThe First Java Program

class Welcome {

/* The Welcome Program by J M Bishop Dec 96 ------------------- Illustrates a simple program displaying a message. */

public static void main (String [ ] args) { System.out.println("Welcome to Java!"); }}

A statement (instruction) to display a message

Page 17: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1717

The First Java ProgramThe First Java Program

class Welcome {

/* The Welcome Program by J M Bishop Dec 96 ------------------- Illustrates a simple program displaying a message. */

public static void main (String [ ] args) { System.out.println("Welcome to Java!"); }}

After every statement, there must be a semi-colon!

Page 18: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1818

The First Java ProgramThe First Java Program

class Welcome {

/* The Welcome Program by J M Bishop Dec 96 ------------------- Illustrates a simple program displaying a message. */

public static void main (String [ ] args) { System.out.println("Welcome to Java!"); }}

How to ask the computer to act according to the

instructions in this program?

Page 19: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1919

The First Java ProgramThe First Java Program

Change to the directory containing tChange to the directory containing the file he file Welcome.javaWelcome.java

TypeTypejavac Welcome.javajavac Welcome.java

It generates a new file It generates a new file Welcome.classWelcome.class Type (without Type (without .class.class))

java Welcomejava Welcome What’s the result?What’s the result?

Page 20: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2020

Object-Oriented Object-Oriented NomenclatureNomenclature ““ClassClass” means a category of things” means a category of things

– A class name can be used in Java as the type A class name can be used in Java as the type of a field or local variable or as the return of a field or local variable or as the return type of a function (method)type of a function (method)

““ObjectObject” means a particular item that ” means a particular item that belongs to a class, also called an belongs to a class, also called an ““instanceinstance””

For example, consider the following line:For example, consider the following line:

StringString s1s1 = " = "HelloHello";";– Here, Here, StringString is the class, and the variable is the class, and the variable s1s1

and the value "and the value "HelloHello" are objects (or " are objects (or “instances of the String class”) “instances of the String class”)

Page 21: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2121

Example 1: Instance Example 1: Instance Variables (“Fields” or “Data Variables (“Fields” or “Data Members”)Members”)

class Ship1 {class Ship1 {

public double x, y, speed, public double x, y, speed, direction;direction;

public String name;public String name;

}}

public class Test1 {public class Test1 {

public static void main(String[] public static void main(String[] args) {args) {

Ship1 Ship1 s1s1 = = new Ship1();new Ship1();

s1.xs1.x = 0.0; = 0.0;

s1.ys1.y = 0.0; = 0.0;

s1.speeds1.speed = 1.0; = 1.0;

s1.directions1.direction = 0.0; // East = 0.0; // East

s1.names1.name = "Ship1"; = "Ship1";

Ship1 Ship1 s2s2 = = new Ship1();new Ship1();

s2.x = 0.0;s2.x = 0.0;

s2.y = 0.0;s2.y = 0.0;

s2.speed = 2.0;s2.speed = 2.0;

s2.direction = 135.0; // Northwests2.direction = 135.0; // Northwest

s2.name = "Ship2";s2.name = "Ship2";

......

......

s1.x = s1.x + s1.speeds1.x = s1.x + s1.speed

* Math.cos(s1.direction * Math.PI / 180.0);* Math.cos(s1.direction * Math.PI / 180.0);

s1.y = s1.y + s1.speeds1.y = s1.y + s1.speed

* Math.sin(s1.direction * Math.PI / 180.0);* Math.sin(s1.direction * Math.PI / 180.0);

s2.x = s2.x + s2.speeds2.x = s2.x + s2.speed

* Math.cos(s2.direction * Math.PI / 180.0);* Math.cos(s2.direction * Math.PI / 180.0);

s2.y = s2.y + s2.speeds2.y = s2.y + s2.speed

* Math.sin(s2.direction * Math.PI / 180.0);* Math.sin(s2.direction * Math.PI / 180.0);

System.out.println(s1.name + " is at ("System.out.println(s1.name + " is at ("

+ s1.x + "," + s1.y + ").");+ s1.x + "," + s1.y + ").");

System.out.println(s2.name + " is at ("System.out.println(s2.name + " is at ("

+ s2.x + "," + s2.y + ").");+ s2.x + "," + s2.y + ").");

}}

}}

Page 22: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2222

Instance Variables: Instance Variables: ResultsResults Compiling and Running:Compiling and Running:

javacjavac Test1.java Test1.java

javajava Test1 Test1

Output:Output:

Ship1 is at (1,0).Ship1 is at (1,0).

Ship2 is at (-1.41421,1.41421).Ship2 is at (-1.41421,1.41421).

Page 23: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2323

Example 1: Major Example 1: Major PointsPoints Java naming conventionJava naming convention Format of class definitionsFormat of class definitions Creating classes with “new”Creating classes with “new”

– Object referenceObject reference Accessing fields with Accessing fields with

“variableName.fieldName”“variableName.fieldName”

Page 24: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2424

Java Naming Java Naming ConventionsConventions Leading uppercase letter in class Leading uppercase letter in class

namename

public class public class MyClassMyClass { { ... ... }}

Leading lowercase letter in field, local Leading lowercase letter in field, local variable, and method (function) variable, and method (function) namesnames– myFieldmyField, , myVarmyVar, , myMethodmyMethod

Page 25: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2525

First Look at Java First Look at Java ClassesClasses The general form of a simple class isThe general form of a simple class is

modifier class Classname {modifier class Classname { modifier data-type modifier data-type field1field1;; modifier data-type modifier data-type field2field2;; ...... modifier data-type modifier data-type fieldNfieldN;;

modifier Return-Type modifier Return-Type methodName1methodName1(parameters) {(parameters) { //statements//statements }} ...... modifier Return-Type modifier Return-Type methodName2methodName2(parameters) {(parameters) { //statements//statements }}}}

Page 26: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2626

Objects and Objects and ReferencesReferences Once a class is defined, you can easily Once a class is defined, you can easily

declare a variable (object reference) of the declare a variable (object reference) of the classclass

ShipShip s1, s2; s1, s2; PointPoint start; start;ColorColor blue; blue;

Object references are initially Object references are initially nullnull – The The nullnull value is a distinct type in Java and should value is a distinct type in Java and should

not be considered equal to zero not be considered equal to zero – A primitive data type cannot be cast to an objectA primitive data type cannot be cast to an object

The The newnew operator is required to explicitly operator is required to explicitly create the object that is referencedcreate the object that is referenced

ClassName variableName = ClassName variableName = new ClassName();new ClassName();

Page 27: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2727

Object ReferenceObject Reference

Like a call number in the library.Like a call number in the library.– A call number A call number refersrefers to a real/physical book to a real/physical book

object.object. No matter how many times you copy a call No matter how many times you copy a call

number, it is still referring to the number, it is still referring to the same same objectobject..– Holding QA123.45.c1 affects the user who Holding QA123.45.c1 affects the user who

borrowed borrowed the same bookthe same book.. Unless you create a new one, e.g. buying a Unless you create a new one, e.g. buying a

new book, you won’t get a new call number.new book, you won’t get a new call number.– QA123.45.c1 and QA123.45.c2QA123.45.c1 and QA123.45.c2

Page 28: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2828

Accessing Instance Accessing Instance VariablesVariables

Use a dot between the variable name and the field name:Use a dot between the variable name and the field name:

variableNamevariableName..fieldNamefieldName

For example, Java has a built-in class called For example, Java has a built-in class called PointPoint that that has has xx and and yy fields fields

PointPoint pp = = newnew PointPoint(2, 3); (2, 3); // Build a Point object// Build a Point objectint xSquared = int xSquared = pp.x * .x * pp.x; .x; // xSquared is 4// xSquared is 4int xPlusY = int xPlusY = pp.x + .x + pp.y; .y; // xPlusY is 5// xPlusY is 5pp.x = 7;.x = 7;xSquared = xSquared = pp.x * .x * pp.x; .x; // Now xSquared is 49// Now xSquared is 49

One major exception applies to the “access fields through One major exception applies to the “access fields through varName.fieldName” rulevarName.fieldName” rule– Methods can access fields of current object without varNameMethods can access fields of current object without varName– This will be explained when methods (functions) are This will be explained when methods (functions) are

discusseddiscussed

Page 29: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2929

Example 2: MethodsExample 2: Methodsclassclass Ship2Ship2 {{

publicpublic doubledouble x=0.0, y=0.0, speed=1.0, direction=0.0; x=0.0, y=0.0, speed=1.0, direction=0.0;

publicpublic StringString name = "UnnamedShip"; name = "UnnamedShip";

privateprivate doubledouble degreesToRadiansdegreesToRadians((doubledouble degrees degrees) ) {{

return(degrees * Math.PI / 180.0);return(degrees * Math.PI / 180.0);

}}

publicpublic voidvoid move move() () {{

doubledouble angle = angle = degreesToRadiansdegreesToRadians(direction);(direction);

x = x + speed * Math.cos(angle);x = x + speed * Math.cos(angle);

y = y + speed * Math.sin(angle);y = y + speed * Math.sin(angle);

}}

publicpublic voidvoid printLocation printLocation() () {{

System.out.println(name + " is at (" + x + "," + y + System.out.println(name + " is at (" + x + "," + y + ").");").");

}}

}}

Page 30: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3030

Methods (Continued)Methods (Continued)publicpublic class Test2 { class Test2 { publicpublic static void main(String[] args) { static void main(String[] args) { Ship2 s1 = new Ship2();Ship2 s1 = new Ship2(); s1.name = "Ship1";s1.name = "Ship1"; Ship2 s2 = new Ship2();Ship2 s2 = new Ship2(); s2.direction = 135.0; // Northwests2.direction = 135.0; // Northwest s2.speed = 2.0;s2.speed = 2.0; s2.name = "Ship2";s2.name = "Ship2"; s1.move();s1.move(); s2.move();s2.move(); s1.printLocation();s1.printLocation(); s2.printLocation();s2.printLocation(); }}}}

Compiling and Running:Compiling and Running:javac Test2.javajavac Test2.java

java Test2java Test2

Output:Output:Ship1 is at (1,0).Ship1 is at (1,0).

Ship2 is at (-Ship2 is at (-1.41421,1.41421).1.41421,1.41421).

Page 31: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3131

Example 2: Major Example 2: Major PointsPoints Format of method definitionsFormat of method definitions Methods that access local fieldsMethods that access local fields Calling methodsCalling methods Static methodsStatic methods Default values for fieldsDefault values for fields public/private distinctionpublic/private distinction

Page 32: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3232

Defining MethodsDefining Methods(Functions Inside (Functions Inside Classes)Classes) Basic method declaration:Basic method declaration:

publicpublic ReturnTypeReturnType methodName( methodName(type1type1 arg1, arg1, type2type2 arg2, ...) arg2, ...) {{

...... returnreturn(something of ReturnType);(something of ReturnType); }}

Exception to this format: if you declare the Exception to this format: if you declare the return type as return type as voidvoid– This special syntax that means “this method isn’t This special syntax that means “this method isn’t

going to return a value – it is just going to do some going to return a value – it is just going to do some side effect like printing on the screen” side effect like printing on the screen”

– In such a case you do not need (in fact, are not In such a case you do not need (in fact, are not permitted), a permitted), a returnreturn statement that includes a statement that includes a value to be returned.value to be returned.

Page 33: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3333

Examples of Defining Examples of Defining MethodsMethods Here are two examples:Here are two examples:

– The first squares an integer The first squares an integer – The second returns the faster of two The second returns the faster of two ShipShip objects, assuming that a class called objects, assuming that a class called ShipShip

has been defined that has a field named has been defined that has a field named speedspeed

// Example function call: // Example function call: // int val = square(7);// int val = square(7); publicpublic intint square square((int xint x) { return(x*x); }) { return(x*x); }

// Example function call:// Example function call: // Ship faster = fasterShip(someShip, // Ship faster = fasterShip(someShip, someOtherShip);someOtherShip); publicpublic ShipShip fasterShip fasterShip((ShipShip ship1, ship1, ShipShip ship2 ship2) {) { if (ship1.speed > ship2.speed) { return(ship1); }if (ship1.speed > ship2.speed) { return(ship1); } else { return(ship2); }else { return(ship2); } }}

Page 34: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3434

Exception to the “Field Exception to the “Field Access with Dots” RuleAccess with Dots” Rule You normally access a field through - You normally access a field through -

variableNamevariableName..fieldNamefieldName

but an exception is when a method of a class wants to but an exception is when a method of a class wants to access fields of that same class. In that case, omit the access fields of that same class. In that case, omit the variable name and the dotvariable name and the dot– For example, a move method within the Ship class might do:For example, a move method within the Ship class might do:

publicpublic voidvoid movemove() () {{ x = x + speed * Math.cos(direction);x = x + speed * Math.cos(direction); ...... }}

– Here, Here, xx, , speedspeed, and , and directiondirection are all fields within the class are all fields within the class that the that the movemove method belongs to, so method belongs to, so movemove can refer to the can refer to the fields directlyfields directly

– As we’ll see later, you still can use the As we’ll see later, you still can use the variableNamevariableName..fieldNamefieldName approach, and Java invents a approach, and Java invents a variable called variable called thisthis that can be used for that purpose that can be used for that purpose

Page 35: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3535

Calling MethodsCalling Methods

The term “The term “methodmethod” means “function associated with ” means “function associated with an object” (i.e., “member function”)an object” (i.e., “member function”)– The usual way that you call a method is by doing the The usual way that you call a method is by doing the

following:following:

variableNamevariableName..methodNamemethodName((argumentsToMethodargumentsToMethod););

For example, the built-in For example, the built-in StringString class has a method class has a method called called toUpperCasetoUpperCase that returns an uppercase that returns an uppercase variation of a variation of a StringString – This method doesn’t take any arguments, so you just put This method doesn’t take any arguments, so you just put

empty parentheses after the function (method) name. empty parentheses after the function (method) name.

StringString s1 = "Hello"; s1 = "Hello";

StringString s2 = s1.toUpperCase(); s2 = s1.toUpperCase(); // s2 is now "HELLO"// s2 is now "HELLO"

Page 36: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3636

Calling Methods Calling Methods (Continued)(Continued)

There are two exceptions to requiring a variable There are two exceptions to requiring a variable name for a method callname for a method call– Calling a method defined inside the current class definition Calling a method defined inside the current class definition – Functions (methods) that are declared “Functions (methods) that are declared “staticstatic””

Calling a method that is defined inside the current Calling a method that is defined inside the current class class – You don’t need the variable name and the dotYou don’t need the variable name and the dot– For example, a For example, a ShipShip class might define a method called class might define a method called

degreeesToRadiansdegreeesToRadians, then, within another function in the same , then, within another function in the same class definition, do this:class definition, do this:

doubledouble angleangle = = degreesToRadiansdegreesToRadians((directiondirection););

No variable name and dot is required in front of No variable name and dot is required in front of degreesToRadiansdegreesToRadians since it is defined in the same class as the since it is defined in the same class as the method that is calling it method that is calling it

Page 37: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3737

Static MethodsStatic Methods

Static functions typically do not need to access any Static functions typically do not need to access any fields within their class and are almost like global fields within their class and are almost like global functions in other languagesfunctions in other languages

You can call a static method through the class You can call a static method through the class namename

ClassNameClassName..functionNamefunctionName((argumentsarguments););

– For example, the For example, the MathMath class has a static method called class has a static method called coscos that expects a that expects a doubledouble precision number as an argument precision number as an argument

So you can call So you can call Math.cos(3.5)Math.cos(3.5) without ever having any without ever having any object (instance) of the object (instance) of the MathMath class class

Note on the Note on the mainmain method method– Since the system calls Since the system calls mainmain without first creating an object, without first creating an object,

staticstatic methods are the only type of methods that methods are the only type of methods that mainmain can call can call directly (i.e. without building an object and calling the method of directly (i.e. without building an object and calling the method of that object) that object)

Page 38: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3838

Modifier - Method Modifier - Method VisibilityVisibility public public / / privateprivate distinction distinction

– A declaration of A declaration of privateprivate means that “outside” means that “outside” methods can’t call it -- only methods within the methods can’t call it -- only methods within the same class cansame class can

for example, the for example, the mainmain method of the method of the Test2Test2 class class could could notnot have done have done

doubledouble x = s1. x = s1.degreesToRadiansdegreesToRadians(2.2);(2.2);– causes an error at compile time causes an error at compile time

– Only say Only say publicpublic for methods that you want to for methods that you want to guarantee your class will make available to users guarantee your class will make available to users

– You are free to change or eliminate private You are free to change or eliminate private methods without telling users of your class aboutmethods without telling users of your class about

Page 39: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3939

Declaring Variables in Declaring Variables in MethodsMethods When you declare a local variable inside of a When you declare a local variable inside of a

method, the normal declaration syntax looks method, the normal declaration syntax looks like:like:

TypeType varNamevarName = = valuevalue;;

The value part can be:The value part can be:– A constant, A constant, – Another variable, Another variable, – A function (method) call, A function (method) call, – A “constructor” invocation (a special type of function A “constructor” invocation (a special type of function

prefaced by prefaced by newnew that builds an object), that builds an object), – Some special syntax that builds an object without Some special syntax that builds an object without

explicitly calling a constructor (e.g., strings)explicitly calling a constructor (e.g., strings)

Page 40: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4040

Declaring Variables in Declaring Variables in Methods:Methods:ExamplesExamples

int x = 3; int x = 3; int y = x;int y = x;

// Special syntax for building a String object// Special syntax for building a String objectStringString s1 = "Hello"; s1 = "Hello";

// Building an object the normal way// Building an object the normal wayStringString s2 = new String("Goodbye"); s2 = new String("Goodbye"); StringString s3 = s2; s3 = s2;StringString s4 = s3.toUpperCase(); s4 = s3.toUpperCase(); // Result: s4 is "GOODBYE"// Result: s4 is "GOODBYE"

// Assume you defined a findFastestShip method that // Assume you defined a findFastestShip method that // returns a Ship// returns a ShipShipShip ship1 = new Ship(); ship1 = new Ship(); ShipShip ship2 = ship1; ship2 = ship1;ShipShip ship3 = findFastestShip(); ship3 = findFastestShip();

Page 41: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4141

Example 3: Example 3: ConstructorsConstructorsclass Ship3 {class Ship3 {

public double x, y, speed, direction;public double x, y, speed, direction; public String name;public String name;

publicpublic Ship3Ship3((double x, double y,double x, double y, double speed, double direction,double speed, double direction, String nameString name)) {{ this.x = x; this.x = x; // "this" differentiates instance vars// "this" differentiates instance vars this.y = y; this.y = y; // from local vars.// from local vars. this.speed = speed;this.speed = speed; this.direction = direction;this.direction = direction; this.name = name;this.name = name; }} private double degreesToRadiansprivate double degreesToRadians

(double degrees) (double degrees) {{

return(degrees * Math.PI / 180.0);return(degrees * Math.PI / 180.0); }} ......

public void move() {public void move() { double angle = double angle =

degreesToRadians(direction);degreesToRadians(direction); x = x + speed * Math.cos(angle);x = x + speed * Math.cos(angle); y = y + speed * Math.sin(angle);y = y + speed * Math.sin(angle); }} public void printLocation() {public void printLocation() { System.out.println(name + " is at System.out.println(name + " is at

("(" + x + "," + y + ").");+ x + "," + y + ")."); }}}}public class Test3 {public class Test3 { public static void main(String[] public static void main(String[]

args) {args) { Ship3 s1 = Ship3 s1 = newnew Ship3Ship3((0.0, 0.0, 0.0, 0.0,

1.0,1.0, 0.0, "Ship1"0.0, "Ship1"););

Ship3 s2 = Ship3 s2 = newnew Ship3Ship3((0.0, 0.0, 0.0, 0.0, 2.0,2.0,

135.0, 135.0, "Ship2""Ship2"););

s1.move(); s2.move();s1.move(); s2.move(); s1.printLocation(); s1.printLocation();

s2.printLocation();s2.printLocation(); }}}}

Page 42: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4242

Constructor Example: Constructor Example: ResultsResults Compiling and Running:Compiling and Running:

javac Test3.javajavac Test3.java

java Test3java Test3

Output:Output:Ship1 is at (1,0).Ship1 is at (1,0).

Ship2 is at (-1.41421,1.41421).Ship2 is at (-1.41421,1.41421).

Page 43: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4343

ConstructorsConstructors

Constructors are special functions called when a Constructors are special functions called when a class is created with class is created with newnew– Constructors are especially useful for supplying values of Constructors are especially useful for supplying values of

fieldsfields– Constructors are declared through:Constructors are declared through:

publicpublic ClassNameClassName((argsargs) ) {{ ......}}

– constructor name must exactly match the class nameconstructor name must exactly match the class name– Constructors have Constructors have no return typeno return type (not even (not even voidvoid), unlike a ), unlike a

regular methodregular method– Java automatically provides a zero-argument constructor if Java automatically provides a zero-argument constructor if

and only if the class doesn’t define it’s own constructor and only if the class doesn’t define it’s own constructor That’s why you could sayThat’s why you could say

Ship1Ship1 s1 = s1 = newnew Ship1(); Ship1(); in the first example, even though a constructor was never in the first example, even though a constructor was never

defineddefined

Page 44: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4444

The The thisthis Variable Variable

The The thisthis object reference can be used inside object reference can be used inside any non-static method to refer to the current any non-static method to refer to the current objectobject

The common uses of the The common uses of the thisthis reference are: reference are:1.1. To pass a reference to the current object as a To pass a reference to the current object as a

parameter to other methodsparameter to other methods

someMethod(this);someMethod(this);

2.2. To resolve name conflictsTo resolve name conflicts Using Using thisthis permits the use of instance variables in permits the use of instance variables in

methods that have local variables with the same namemethods that have local variables with the same name

– Note that it is only necessary to say Note that it is only necessary to say thisthis..fieldNamefieldName when you have a local variable and a class field with when you have a local variable and a class field with the same name; otherwise just use the same name; otherwise just use fieldNamefieldName with no with no thisthis

Page 45: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4545

SummarySummary

Class names should start with uppercase; method Class names should start with uppercase; method names with lowercasenames with lowercase

Methods must define a return type or Methods must define a return type or voidvoid if no if no result is returnedresult is returned

Static methods do not require an instance of the Static methods do not require an instance of the class; static methods can be accessed through the class; static methods can be accessed through the class nameclass name

““thisthis”” reference in a class refers to the reference in a class refers to the currentcurrent object object

Class constructors do not declare a Class constructors do not declare a returnreturn type type Java performs its own memory management and Java performs its own memory management and

requires no destructorsrequires no destructors

Page 46: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4646

Break Time – 15 Break Time – 15 minutesminutes

Page 47: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4747

Part B: Advanced OOPart B: Advanced OO

OverloadingOverloading Designing “real” classesDesigning “real” classes InheritanceInheritance Advanced topicsAdvanced topics

– Abstract classesAbstract classes– InterfacesInterfaces– Understanding polymorphismUnderstanding polymorphism– using packagesusing packages– Visibility modifiers Visibility modifiers

Page 48: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4848

Example 4: Example 4: OverloadingOverloadingclass Ship4 {class Ship4 {

public double x=0.0, y=0.0, speed=1.0, direction=0.0;public double x=0.0, y=0.0, speed=1.0, direction=0.0; public String name;public String name;

public public Ship4(double x, double y, double speed, Ship4(double x, double y, double speed, double direction, String name)double direction, String name) { {

this.x = x;this.x = x; this.y = y;this.y = y; this.speed = speed;this.speed = speed; this.direction = direction;this.direction = direction; this.name = name;this.name = name; }} public public Ship4(String name)Ship4(String name) { { this.name = name;this.name = name; }} private double degreesToRadians(double degrees) {private double degreesToRadians(double degrees) { return(degrees * Math.PI / 180.0);return(degrees * Math.PI / 180.0); }} ......

Page 49: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4949

Overloading Overloading (Continued)(Continued)

......

public void move() {public void move() { move(1);move(1); }} public void move(int steps) {public void move(int steps) { double angle = degreesToRadians(direction);double angle = degreesToRadians(direction); x = x + (double)steps * speed * Math.cos(angle);x = x + (double)steps * speed * Math.cos(angle); y = y + (double)steps * speed * Math.sin(angle);y = y + (double)steps * speed * Math.sin(angle); }}

public void printLocation() {public void printLocation() { System.out.println(name + " is at ("+ x + "," + y + ").");System.out.println(name + " is at ("+ x + "," + y + ")."); }}}}

Page 50: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5050

Overloading: Testing Overloading: Testing and Resultsand Results

public class Test4 {public class Test4 { public static void main(String[] args) {public static void main(String[] args) { Ship4 s1 = new Ship4("Ship1"); Ship4 s1 = new Ship4("Ship1"); Ship4 s2 = new Ship4(0.0, 0.0, 2.0, Ship4 s2 = new Ship4(0.0, 0.0, 2.0, 135.0,"Ship2");135.0,"Ship2"); s1.move();s1.move(); s2.move(3);s2.move(3); s1.printLocation();s1.printLocation(); s2.printLocation();s2.printLocation(); }}}}

Compiling and Running:Compiling and Running:javac Test4.javajavac Test4.javajava Test4java Test4

Output:Output:Ship1 is at (1,0).Ship1 is at (1,0).Ship2 is at (-4.24264,4.24264).Ship2 is at (-4.24264,4.24264).

Page 51: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5151

Overloading: Major Overloading: Major PointsPoints IdeaIdea

– Allows you to define more than one function or Allows you to define more than one function or constructor with the same nameconstructor with the same name

Overloaded functions or constructors must differ in the Overloaded functions or constructors must differ in the number or types of their arguments (or both), so that number or types of their arguments (or both), so that Java can always tell which one you meanJava can always tell which one you mean

Simple examples:Simple examples:– Here are two square methods that differ only in the Here are two square methods that differ only in the

type of the argument; they would both be permitted type of the argument; they would both be permitted inside the same class definition.inside the same class definition.

// square(4) is 16// square(4) is 16publicpublic intint square(int x)square(int x) { return(x*x); } { return(x*x); }

// square("four") is "four four"// square("four") is "four four"publicpublic StringString square(String s)square(String s) { return(s + " " + s); } { return(s + " " + s); }

Page 52: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5252

Example 5: OOP Example 5: OOP Design and UsageDesign and Usage/** Ship example to demonstrate OOP in Java. *//** Ship example to demonstrate OOP in Java. */

public class Ship {public class Ship { privateprivate double x=0.0, y=0.0, speed=1.0, direction=0.0; double x=0.0, y=0.0, speed=1.0, direction=0.0; privateprivate String name; String name; … … /** Get current X location. *//** Get current X location. */

public double public double getXgetX() {() { return(x);return(x); }}

/** Set current X location. *//** Set current X location. */ public void public void setXsetX(double x) {(double x) { this.x = x;this.x = x; }}

Page 53: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5353

Example 5: Major Example 5: Major PointsPoints EncapsulationEncapsulation

– Lets you change internal representation Lets you change internal representation and data structures and data structures without users of your without users of your class changing their codeclass changing their code

– Lets you put constraints on values Lets you put constraints on values without without users of your class changing their codeusers of your class changing their code

– Lets you perform arbitrary side effects Lets you perform arbitrary side effects without users of your class changing their without users of your class changing their codecode

Comments and JavaDocComments and JavaDoc– Will be covered in the tutorialWill be covered in the tutorial

Page 54: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5454

Example 6: InheritanceExample 6: Inheritancepublic class Speedboat public class Speedboat extends extends ShipShip { { private String color = "red";private String color = "red"; public Speedboat(String name) {public Speedboat(String name) { super(name);super(name); setSpeed(20);setSpeed(20); }} public Speedboat(double x, double y,public Speedboat(double x, double y, double speed, double direction,double speed, double direction, String name, String color) {String name, String color) { super(x, y, speed, direction, name);super(x, y, speed, direction, name); setColor(color);setColor(color); }} public void public void printLocation()printLocation() { { System.out.print(getColor().toUpperCase() + " System.out.print(getColor().toUpperCase() + "

");"); super.printLocation();super.printLocation(); }} ......}}

Page 55: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5555

Inheritance Example: Inheritance Example: TestingTestingpublicpublic class SpeedboatTest { class SpeedboatTest { publicpublic static void main(String[] args) { static void main(String[] args) { SpeedboatSpeedboat s1 = s1 = newnew Speedboat("Speedboat1"); Speedboat("Speedboat1"); SpeedboatSpeedboat s2 = s2 = newnew Speedboat(0.0, 0.0, 2.0, Speedboat(0.0, 0.0, 2.0,

135.0,135.0, "Speedboat2", "blue");"Speedboat2", "blue"); ShipShip s3 = s3 = newnew Ship(0.0, 0.0, 2.0, 135.0, "Ship1"); Ship(0.0, 0.0, 2.0, 135.0, "Ship1"); s1.move();s1.move(); s2.move();s2.move(); s3.move();s3.move(); s1.printLocation();s1.printLocation(); s2.printLocation();s2.printLocation(); s3.printLocation();s3.printLocation(); }}}}

Page 56: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5656

Inheritance Example: Inheritance Example: ResultResult Compiling and Running:Compiling and Running:

javac SpeedboatTest.javajavac SpeedboatTest.java

– The above calls javac on The above calls javac on Speedboat.javaSpeedboat.java and and Ship.javaShip.java automatically automatically

java SpeedboatTestjava SpeedboatTest

OutputOutputRED Speedboat1 is at (20,0).RED Speedboat1 is at (20,0).BLUE Speedboat2 is at (-1.41421,1.41421).BLUE Speedboat2 is at (-1.41421,1.41421).Ship1 is at (-1.41421,1.41421).Ship1 is at (-1.41421,1.41421).

Page 57: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5757

Example 6: Major Example 6: Major PointsPoints Format for defining subclassesFormat for defining subclasses Using inherited methodsUsing inherited methods Using super(…) for inherited Using super(…) for inherited

constructorsconstructors– OnlyOnly when the zero-arg constructor is when the zero-arg constructor is

not OKnot OK Using super.someMethod(…) for Using super.someMethod(…) for

inherited methods inherited methods – OnlyOnly when there is a name conflict when there is a name conflict

Page 58: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5858

InheritanceInheritance

Syntax for defining subclassesSyntax for defining subclassespublic class NewClass extends OldClass {public class NewClass extends OldClass { ......}}

Nomenclature:Nomenclature:– The The existing classexisting class is called the is called the superclasssuperclass, , base classbase class or or parent parent

classclass– The The new classnew class is called the is called the subclasssubclass, , derived classderived class or or child classchild class

Effect of inheritanceEffect of inheritance– Subclasses automatically have all public fields and methods of Subclasses automatically have all public fields and methods of

the parent classthe parent class– You don’t need any special syntax to access the inherited fields You don’t need any special syntax to access the inherited fields

and methods; you use the exact same syntax as with locally and methods; you use the exact same syntax as with locally defined fields or methods. defined fields or methods.

– You can also add in fields or methods not available in the You can also add in fields or methods not available in the superclasssuperclass

Java doesn’t support multiple inheritanceJava doesn’t support multiple inheritance

Page 59: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5959

Inherited constructors Inherited constructors and super(...)and super(...) When you instantiate an object of a subclass, the system When you instantiate an object of a subclass, the system

will automatically call the superclass constructor firstwill automatically call the superclass constructor first– By default, the zero-argument superclass constructor is By default, the zero-argument superclass constructor is

called unless a different constructor is specifiedcalled unless a different constructor is specified– Access the constructor in the superclass through Access the constructor in the superclass through

supersuper((argsargs))

– If If super(…)super(…) is used in a subclass constructor, then is used in a subclass constructor, then super(…)super(…) must be the first statement in the constructor must be the first statement in the constructor

Constructor life-cycleConstructor life-cycle– Each constructor has three phases:Each constructor has three phases:

1.1. Invoke the constructor of the superclassInvoke the constructor of the superclass2.2. Initialize all instance variables based on their initialization Initialize all instance variables based on their initialization

statementsstatements3.3. Execute the body of the constructorExecute the body of the constructor

Page 60: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6060

Overridden methods Overridden methods and super.method(...)and super.method(...) When a class defines a method using the When a class defines a method using the same name, same name,

return type, and argumentsreturn type, and arguments as a method in the as a method in the superclass, then the class superclass, then the class overridesoverrides the method in the the method in the superclasssuperclass– Only non-static methods can be overriddenOnly non-static methods can be overridden

If there is a locally defined method and an inherited If there is a locally defined method and an inherited method that take the same arguments, you can use the method that take the same arguments, you can use the following to refer to the inherited method following to refer to the inherited method

super.methodName(...)super.methodName(...)

– Successive use of Successive use of supersuper (super.super.methodName) will (super.super.methodName) will not access overridden methods higher up in the hierarchy; not access overridden methods higher up in the hierarchy; supersuper can only be used to invoke overridden methods can only be used to invoke overridden methods from within the class that does the overridingfrom within the class that does the overriding

Page 61: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6161

Advanced OOP TopicsAdvanced OOP Topics

Abstract classesAbstract classes InterfacesInterfaces Polymorphism detailsPolymorphism details PackagesPackages Visibility other than public or Visibility other than public or

privateprivate

Page 62: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6262

Abstract ClassesAbstract Classes

IdeaIdea– Abstract classes permit declaration of classes that define Abstract classes permit declaration of classes that define

only part of an implementation, leaving the subclasses to only part of an implementation, leaving the subclasses to provide the detailsprovide the details

A class is considered abstract if at least one method in A class is considered abstract if at least one method in the class has no implementation the class has no implementation – An abstract method has no implementation (known in C++ An abstract method has no implementation (known in C++

as a pure virtual function)as a pure virtual function)– Any class with an abstract method must be declared abstractAny class with an abstract method must be declared abstract– If the subclass overrides all the abstract methods in the If the subclass overrides all the abstract methods in the

superclass, than an object of the subclass can be superclass, than an object of the subclass can be instantiatedinstantiated

An abstract class can contain instance variables and An abstract class can contain instance variables and methods that are fully implementedmethods that are fully implemented– Any subclass can override a concrete method inherited from Any subclass can override a concrete method inherited from

the superclass and declare the method abstractthe superclass and declare the method abstract

Page 63: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6363

Abstract Classes Abstract Classes (Continued)(Continued) An abstract class cannot be instantiated, An abstract class cannot be instantiated,

however references to an abstract class can however references to an abstract class can be declared be declared

public public abstractabstract ThreeDshape { ThreeDshape { public abstract void drawShape( Graphics g );public abstract void drawShape( Graphics g ); public abstract void resize( double scale );public abstract void resize( double scale ); }}

ThreeDshape s1; ThreeDshape s1; ThreeDshape[] arrayOfShapes = new ThreeDshape[20]; ThreeDshape[] arrayOfShapes = new ThreeDshape[20];

Classes from which objects can be Classes from which objects can be instantiated are called instantiated are called concrete classesconcrete classes

Page 64: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6464

InterfacesInterfaces

IdeaIdea– Interfaces define a Java type consisting purely of Interfaces define a Java type consisting purely of

constants and abstract methodsconstants and abstract methods– An interface does not implement any of the An interface does not implement any of the

methods, but imposes a design structure on any methods, but imposes a design structure on any class that uses the interfaceclass that uses the interface

– A class that implements an interface must either A class that implements an interface must either provide definitions for all methods or declare itself provide definitions for all methods or declare itself abstractabstract

Page 65: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6565

Interfaces (Continued)Interfaces (Continued)

ModifiersModifiers– All methods in an interface are implicitly abstract and All methods in an interface are implicitly abstract and

the keyword abstract is not required in a method the keyword abstract is not required in a method declarationdeclaration

– Data fields in an interface are implicitly Data fields in an interface are implicitly static static finalfinal (constants)(constants)

– All data fields and methods in an interface are All data fields and methods in an interface are implicitly implicitly publicpublicpublic interface Interface1 { DataType CONSTANT1 = value1; DataType CONSTANT2 = value2;

ReturnType1 method1(ArgType1 arg); ReturnType2 method2(ArgType2 arg);}

Page 66: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6666

Interfaces (Continued)Interfaces (Continued)

Extending InterfacesExtending Interfaces– Interfaces can extend other interfaces, which brings rise to Interfaces can extend other interfaces, which brings rise to

sub-interfaces and super-interfacessub-interfaces and super-interfaces– Unlike classes, however, an interface can extend more than Unlike classes, however, an interface can extend more than

one interface at a timeone interface at a time

public interface Displayable public interface Displayable extends Drawable, Printable extends Drawable, Printable {{

// Additonal constants and abstract methods// Additonal constants and abstract methods ...... }} Implementing Multiple InterfacesImplementing Multiple Interfaces

– Interfaces provide a Interfaces provide a formform of multiple inheritance because a of multiple inheritance because a class can implement more than one interface at a timeclass can implement more than one interface at a time

public class Circle public class Circle extends TwoDshape extends TwoDshape implements Drawable, Printable implements Drawable, Printable { { ......}}

Page 67: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6767

PolymorphismPolymorphism

““PolymorphicPolymorphic” literally means “of multiple ” literally means “of multiple shapes” and in the context of object-oriented shapes” and in the context of object-oriented programming, polymorphic means “having programming, polymorphic means “having multiple behavior” multiple behavior”

A polymorphic method results in different A polymorphic method results in different actions depending on the object being actions depending on the object being referencedreferenced – Also known as Also known as late bindinglate binding or or run-time bindingrun-time binding

In practice, polymorphism is used in In practice, polymorphism is used in conjunction with reference arrays to loop conjunction with reference arrays to loop through a collection of objects and to access through a collection of objects and to access each object's polymorphic methodeach object's polymorphic method

Page 68: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6868

Polymorphism: Polymorphism: ExampleExample

public class PolymorphismTest {public class PolymorphismTest { public static void main(String[] args) {public static void main(String[] args) { Ship[] shipsShip[] ships = new Ship[3]; = new Ship[3]; ships[0] = ships[0] = new Shipnew Ship(0.0, 0.0, 2.0, 135.0, "Ship1");(0.0, 0.0, 2.0, 135.0, "Ship1"); ships[1] = ships[1] = new Speedboatnew Speedboat("Speedboat1");("Speedboat1"); ships[2] = ships[2] = new new

SpeedboatSpeedboat(0.0,0.0,2.0,135.0,"Speedboat2","blue");(0.0,0.0,2.0,135.0,"Speedboat2","blue"); for(int i=0; i<ships.length ; i++) {for(int i=0; i<ships.length ; i++) { ships[i].move();ships[i].move(); ships[i].printLocation();ships[i].printLocation(); }} }}}}

Page 69: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6969

Polymorphism: ResultPolymorphism: Result

Compiling and Running:Compiling and Running:

javac PolymorphismTest.javajavac PolymorphismTest.java

java PolymorphismTest java PolymorphismTest

OutputOutput

RED Speedboat1 is at (20,0).RED Speedboat1 is at (20,0).

BLUE Speedboat2 is at (-1.41421,1.41421).BLUE Speedboat2 is at (-1.41421,1.41421).

Ship1 is at (-1.41421,1.41421).Ship1 is at (-1.41421,1.41421).

Page 70: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7070

Creating PackagesCreating Packages

A A packagepackage lets you group classes in subdirectories lets you group classes in subdirectories to to avoid accidental name conflictsavoid accidental name conflicts

– To create a package:To create a package:1.1. Create a subdirectory with the same name as the desired Create a subdirectory with the same name as the desired

package and place the source files in that directorypackage and place the source files in that directory2.2. Add a package statement to each fileAdd a package statement to each file

package packagename;package packagename;3.3. Files in the main directory that want to use the package should Files in the main directory that want to use the package should

includeinclude

import packagename.*;import packagename.*; The package statement must be the The package statement must be the first statementfirst statement

in the filein the file If a package statement is omitted from a file, then If a package statement is omitted from a file, then

the code is part of the default package that has no the code is part of the default package that has no namename

Page 71: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7171

Package DirectoriesPackage Directories

The package hierarchy reflects the file The package hierarchy reflects the file system directory structuresystem directory structure

– The root of any package must be accessible The root of any package must be accessible through a Java system default directory or through through a Java system default directory or through the the CLASSPATHCLASSPATH environment variable environment variable

Package java.math

Page 72: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7272

Visibility ModifiersVisibility Modifiers

publicpublic– This modifier indicates that the variable or method can This modifier indicates that the variable or method can

be be accessed anywhere an instance of the class is accessed anywhere an instance of the class is accessibleaccessible

– A class may also be designated A class may also be designated publicpublic, which means , which means that any other class can use the class definitionthat any other class can use the class definition

– The name of a public class must match the filename, The name of a public class must match the filename, thus a file can have only one public classthus a file can have only one public class

privateprivate– A A privateprivate variable or method is variable or method is only accessible from only accessible from

methods within the same classmethods within the same class – Declaring a class variable private "hides" the data Declaring a class variable private "hides" the data

within the class, making the data available outside the within the class, making the data available outside the class only through method calls class only through method calls

Page 73: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7373

Visibility Modifiers, Visibility Modifiers, cont.cont. protectedprotected

– Protected variables or methods can only be Protected variables or methods can only be accessed by methods within the class, within accessed by methods within the class, within classes in the same package, and within subclasses classes in the same package, and within subclasses

– Protected variables or methods are inherited by Protected variables or methods are inherited by subclasses of the same or different packagesubclasses of the same or different package

[default][default]– A variable or method has default visibility if a A variable or method has default visibility if a

modifier is omitted modifier is omitted – Default visibility indicates that the variable or Default visibility indicates that the variable or

method can be accessed by methods within the method can be accessed by methods within the class, and within classes in the same packageclass, and within classes in the same package

– Default variables are inherited only by subclasses Default variables are inherited only by subclasses in the same packagein the same package

Page 74: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7474

Protected Visibility: Protected Visibility: ExampleExample

CakeCake, , ChocolateCakeChocolateCake, and , and PiePie inherit a inherit a caloriescalories field field However, if the code in the However, if the code in the CakeCake class had a reference to class had a reference to

object of type object of type PiePie, the protected calories field of the , the protected calories field of the PiePie object could not be accessed in the object could not be accessed in the CakeCake class class – Protected fields of a class are not accessible outside its branch of Protected fields of a class are not accessible outside its branch of

the class hierarchy (unless the complete tree hierarchy is in the the class hierarchy (unless the complete tree hierarchy is in the same package) same package)

Page 75: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7575

Default Visibility: Default Visibility: ExampleExample

Even through inheritance, the fat data field cannot Even through inheritance, the fat data field cannot cross the package boundary cross the package boundary – Thus, the Thus, the fatfat data field is accessible through any data field is accessible through any DessertDessert, , PiePie, ,

and and CakeCake object within any code in the object within any code in the DessertDessert package package – However, the However, the ChocolateCakeChocolateCake class does not have a fat data class does not have a fat data

field, nor can the fat data field of a field, nor can the fat data field of a DessertDessert, , CakeCake, or , or PiePie object object be accessed from code in the be accessed from code in the ChocolateCakeChocolateCake class class

Page 76: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7676

Visibility SummaryVisibility Summary

Variables or methods Variables or methods with this modifiers can with this modifiers can be accessed by be accessed by methods inmethods in

PubliPublicc

PrivatPrivatee

ProtecteProtectedd

DefaulDefaultt

Same classSame class YesYes YesYes YesYes YesYes

Classes in the same Classes in the same PackagePackage

YesYes NoNo YesYes YesYes

SubclassesSubclasses YesYes NoNo YesYes NoNo

Classes in Different Classes in Different PackagePackage

YesYes NoNo NoNo NoNo

Page 77: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7777

Other ModifiersOther Modifiers

finalfinal– For a class, indicates that it cannot be subclassedFor a class, indicates that it cannot be subclassed– For a method or variable, cannot be changed at For a method or variable, cannot be changed at

runtime or overridden in subclassesruntime or overridden in subclasses synchronizedsynchronized

– Sets a lock on a section of code or methodSets a lock on a section of code or method– Only one thread can access the same synchronized Only one thread can access the same synchronized

code at any given timecode at any given time transienttransient

– Variables are not stored in serialized objects sent Variables are not stored in serialized objects sent over the network or stored to diskover the network or stored to disk

nativenative– Indicates that the method is implement using C or Indicates that the method is implement using C or

C++C++

Page 78: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7878

SummarySummary

Overloaded methods/constructors, except for Overloaded methods/constructors, except for the argument list, have identical signaturesthe argument list, have identical signatures

Use Use extendsextends to create a new class that to create a new class that inherits from a superclassinherits from a superclass– Java does not support multiple inheritanceJava does not support multiple inheritance

An inherited method in a subclass can be An inherited method in a subclass can be overridden to provide custom behavioroverridden to provide custom behavior– The original method in the parent class is The original method in the parent class is

accessible through accessible through super.methodName(...)super.methodName(...) Interfaces contain only abstract methods and Interfaces contain only abstract methods and

constantsconstants– A class can A class can implementimplement more than one interface more than one interface

Page 79: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7979

Summary (Continued)Summary (Continued)

With polymorphism, binding of a method to With polymorphism, binding of a method to an object is determined at run-timean object is determined at run-time

The The CLASSPATHCLASSPATH defines in which directories to defines in which directories to look for classeslook for classes

Packages help avoid namespace collisionsPackages help avoid namespace collisions– The package statement must be first statement in The package statement must be first statement in

the source file before any other statementsthe source file before any other statements The four visibility types are: public, private, The four visibility types are: public, private,

protected, and default (no modifier)protected, and default (no modifier)– Protected members can only cross package Protected members can only cross package

boundaries through inheritanceboundaries through inheritance– Default members are only inherited by classes in Default members are only inherited by classes in

the same packagethe same package

Page 80: Object-Oriented Java Programming INE2720 Web Application Software Development Essential Materials.

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

8080

ReferencesReferences

CWP: Chapter 7CWP: Chapter 7 http://java.sun.com/http://java.sun.com/ http://java.sun.com/docs/books/tutorial/http://java.sun.com/docs/books/tutorial/ http://www.ibiblio.org/javafaq/course/http://www.ibiblio.org/javafaq/course/

The End.The End. Thank you for patience!Thank you for patience!