Java OO Concept

28
Java OO Concept Chate Patanothai

description

Java OO Concept. Chate Patanothai. Java: call by value. Method parameters are copied in the parameter variables when a method starts. Any changes to the parameter variables do not affect the original variables. True in all cases; primitives and references. Java: call by value. - PowerPoint PPT Presentation

Transcript of Java OO Concept

Page 1: Java OO Concept

Java OO Concept

Chate Patanothai

Page 2: Java OO Concept

2

Java: call by value

• Method parameters are copied in the parameter variables when a method starts.

• Any changes to the parameter variables do not affect the original variables.

• True in all cases; primitives and references

Page 3: Java OO Concept

3

Java: call by valuepublic static void main(String[] args) { int x = 5; Point p = new Point(2, 3); changeValue(x); changeReferenece(p); changeState(p);} public static void changeValue(int x) {

x = 10;}

public static void changeReference(Point aP) { aP = new Point(5, 5);}

public static void changeState(Point aP) { aP.x = 4; aP.y = 4;}

After returning from changeReference, p is still Point of (2, 3)

After returning from changeState, p is changed to Point of (4, 4)

Page 4: Java OO Concept

4

Package

• A package is a collection of related classes and interfaces providing access protection and namespace management.

• Java classes and interfaces are members of various packages that bundle classes by function: – fundamental classes are in java.lang, – classes for reading and writing (input and

output) are in java.io, – etc.

• Avoid namespace conflict

Page 5: Java OO Concept

5

Creating a package

• Use a package statement at the top of the source file in which the class or the interface is defined.package com.chate.shapes;

public class Oval { // . . .}

package com.chate.shapes;

public class Rectangle { // . . .}

com └─── chate

└─── shapes ├─── Oval.class └─── Rectangle.class

classes in the same package are in the same directory/folder

Page 6: Java OO Concept

6

Naming a package

• By Convention: Companies use their reversed Internet domain name in their package names, like this: com.company.package.

• Name collisions that occur within a single company need to be handled by convention within that company,– com.company.region.package

• Reverse of your email address ([email protected])– com.domain.name

Page 7: Java OO Concept

7

Using package members

• Full qualified namecom.chate.shapes.Oval o = new Oval();

com.chate.shapes.Rectangle r =

new Rectangle()

• Importimport com.chate.shapes.Oval;

import com.chate.shapes.Rectagle;

// to import all members

// import com.chate.shapes.*;

Oval o = new Oval();

Rectangle r = new Rectangle();

Page 8: Java OO Concept

8

Name conflict

• If a member in one package has the same name with a member in another package and both packages are imported, you must use qualified name.import java.awt.*;import com.chate.shapes.*;Rectangle r = new Rectangle(); // error

both packages have Rectangle.class

import java.awt.*;import com.chate.shapes.*;com.chate.shapes.Rectangle r = new Rectangle();

import java.awt.*;import com.chate.shapes.*;java.awt.Rectangle r = new Rectangle();

Page 9: Java OO Concept

9

Access control

Specifier ClassSubcla

ssPackag

eWorld

private protected public package(default)

Page 10: Java OO Concept

10

Multiple inheritance

• Java does not allow having a class extending from more than one class (multiple inheritance is not allowed)

• Use interface instead• A class can implement any number

of interfaces but extend at most one class

Page 11: Java OO Concept

11

What is an Interface?

• a protocol of behavior that can be implemented by any class anywhere in the class hierarchy

• a set of methods but does not implement them (abstract methods)– name, parameters, return type– automatically public

An interface is a named collection of method definitions (without implementations).

Page 12: Java OO Concept

12

Interface

• If a class want to be a Turnable, it must implement all methods defined in Turnable interfacepublic class Car implements Turnable { . . . public void turnLeft() { . . .} public void turnRight() { . . . }}

interface Turnable { void turnLeft(); void turnRight();}

Page 13: Java OO Concept

13

public class Car extends Vehicle implements Turnable, Moveable { // . . . public void turnLeft() { . . . } public void turnRight() { . . . } public void forward() { . . . } public void backward() { . . . }}

Multiple interface inheritance

<<interface>>Turnable

<<interface>>Moveable

Vehicle

Car

interface Turnable { void turnLeft(); void turnRight();}

interface Moveable { void forward(); void backward();}

Page 14: Java OO Concept

14

public class Car extends Vehicle implements Turnable, Moveable { // . . . public void turnLeft() { . . . } public void turnRight() { . . . } public void forward() { . . . } public void backward() { . . . }}

Multiple interface inheritance interface Turnable {

void turnLeft(); void turnRight();}

interface Moveable { void forward(); void backward();}

<<interface>>Turnable

<<interface>>Moveable

Vehicle

Car

<<interface>>Relocateable

Page 15: Java OO Concept

15

public class Human implements Turnable, Moveable { // . . . public void turnLeft() { . . .} public void turnRight() { . . . } public void forward() { . . .} public void backward() { . . . }}

Multiple interface inheritance

<<interface>>Turnable

<<interface>>Moveable

Vehicle

HumanCar

<<interface>>Relocateable

Page 16: Java OO Concept

16

Interfacepublic void uTurn(Object obj) { if (obj instance of Car) { Car c = (Car) obj; c.turnRight(); c.turnRight(); } else if (obj instance of Human) { Human h = (Human) obj; h.turnRight(); h.turnRight(); }}

public void uTurn(Relocateable m) { m.turnRight(); m.turnRight();{

Page 17: Java OO Concept

17

Being a Descendent of Object • Every class in the Java system is a

descendent, direct or indirect, of the Object class.

• This class defines the basic state and behavior that all objects must have, such as – the ability to compare oneself to another object, – to convert to a string, – to wait on a condition variable, – to notify other objects that a condition variable

has changed, – and to return the class of the object.

Page 18: Java OO Concept

18

clone()

equals(Object obj)

hashcode()

finalize()

toString()

getClass()

notify()

notifyAll()

wait(); wait(long timeout);

wait(long timeout, int nanos)

Method summary

Cannot override

Page 19: Java OO Concept

19

The clone() method

• To create an object from an existing objectaCloneableObject.clone()

Page 20: Java OO Concept

20

Clone examplepublic class Stack implements Cloneable { private Vector items;

// code for Stack's methods and constructor not shown protected Object clone() { try { Stack s = (Stack)super.clone(); // clone the stack s.items = (Vector)items.clone(); // clone the vector return s; // return the clone } catch (CloneNotSupportedException e) { // this shouldn't happen because Stack is Cloneable throw new InternalError(); } } } To have clone(), one must implement Cloneable,

otherwise CloneNotSupportedException will be thrown.

Page 21: Java OO Concept

21

Stack aStack = new Stack();

Stack anotherStack = aStack.clone();Stack s = (Stack)super.clone();

s.items = (Vector)items.clone();

return s;

Clone example

aStack

items

[Stack] [Vector]

anotherStack

items

[Stack]

[Vector]

s

Page 22: Java OO Concept

22

More clone example

class A { private int x; public A(int i) { x = i; }} public class CloneDemo1 { public static void main(String args[]) throws CloneNotSupportedException { A obj1 = new A(37); A obj2 = (A)obj1.clone(); }}

compile error:because Object.clone()is a protected method.

Page 23: Java OO Concept

23

More clone exampleclass A { private int x; public A(int i) { x = i; } public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(e.toString()); } }} public class CloneDemo2 {

public static void main(String args[]) throws CloneNotSupportedException { A obj1 = new A(37); A obj2 = (A)obj1.clone(); }}

CloneNotSupportedExceptionis thrown at runtime.

Page 24: Java OO Concept

24

More clone exampleclass A implements Cloneable { private int x; public A(int i) { x = i; } public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(e.toString()); } } public int getx() { return x; }}

public class CloneDemo3 { public static void main(String args[]) throws CloneNotSupportedException { A obj1 = new A(37); A obj2 = (A)obj1.clone(); System.out.println(obj2.getx()); }}

success!

Page 25: Java OO Concept

25

The equals() method• The equals method implements an equivalence

relation on non-null object references: – It is reflexive: for any non-null reference value x,

x.equals(x) should return true. – It is symmetric: for any non-null reference values x and

y, x.equals(y) should return true if and only if y.equals(x) returns true.

– It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.

– It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.

– For any non-null reference value x, x.equals(null) should return false.

Page 26: Java OO Concept

26

The equals() method

aStack.equals(anotherStack);

public boolean equals(Object obj) {

if (this == obj) return true;

if ((obj == null) ||

(obj.getClass() != this.getClass()))

return false;

Stack that = (Stack) obj;

return (that.items.equals(items);

}

Page 27: Java OO Concept

27

The equals() method

aStack.equals(anotherStack);

// for final classpublic boolean equals(Object obj) {

if (this == obj)

return true;

if (!(obj instanceof Stack))

return false;

Stack that = (Stack) obj;

return (that.items.equals(items);

}

There are cases that:x.equals(y) truey.equals(x) falseor vice versa

Page 28: Java OO Concept

28

The hashCode() method

• The value returned by hashCode is an int that maps an object into a bucket in a hash table.

• An object must always produce the same hash code.

• If you override equals, you must override hashCode.

• hashCode must generate equal values for equal objects.public int hashCode() { . . . }