Transcript public int

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
2
Java: call by value
public static void main(String[] args) { After returning from
int x = 5;
changeReference,
Point p = new Point(2, 3);
p is still Point of (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);
}
After returning from
changeState, p is
changed to Point of (4, 4)
public static void changeState(Point aP) {
aP.x = 4;
aP.y = 4;
}
3
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
4
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;
package com.chate.shapes;
public class Oval {
// . . .
}
public class Rectangle {
// . . .
}
com
classes in the same
└─── chate
package are in the
└─── shapes
same directory/folder
├─── Oval.class
└─── Rectangle.class
5
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
6
Using package members
• Full qualified name
com.chate.shapes.Oval o = new Oval();
com.chate.shapes.Rectangle r =
new Rectangle()
• Import
import 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();
7
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();
both packages have
Rectangle.class
// error
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();
8
Access control
Specifier
private
protected
public
package
(default)
Class




Subclass Package





World

9
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
10
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).
11
Interface
interface Turnable {
void turnLeft();
void turnRight();
}
• If a class want to be a Turnable, it must
implement all methods defined in
Turnable interface
public class Car implements Turnable {
. . .
public void turnLeft() { . . .}
public void turnRight() { . . . }
}
12
Multiple interface inheritance
Vehicle
<<interface>>
Moveable
<<interface>>
Turnable
Car
public class Car extends Vehicle
implements Turnable, Moveable
// . . .
public void turnLeft() { . . .
public void turnRight() { . . .
public void forward()
{ . . .
public void backward() { . . .
}
interface Turnable {
void turnLeft();
void turnRight();
}
interface Moveable {
void forward();
void backward();
}
{
}
}
}
}
13
Multiple interface inheritance
Vehicle
<<interface>>
Relocateable
<<interface>>
Moveable
<<interface>>
Turnable
interface Turnable {
void turnLeft();
void turnRight();
}
interface Moveable {
void forward();
void backward();
}
Car
public class Car extends Vehicle
implements Turnable, Moveable
// . . .
public void turnLeft() { . . .
public void turnRight() { . . .
public void forward()
{ . . .
public void backward() { . . .
}
{
}
}
}
}
14
Multiple interface inheritance
Vehicle
<<interface>>
Relocateable
<<interface>>
Moveable
<<interface>>
Turnable
Car
public class Human implements
// . . .
public void turnLeft() { .
public void turnRight() { .
public void forward()
{ .
public void backward() { .
}
Human
Turnable, Moveable {
.
.
.
.
.}
. }
.}
. }
15
Interface
public 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();
{
16
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.
17
Method summary
clone()
equals(Object obj)
hashcode()
finalize()
toString()
getClass()
Cannot override
notify()
notifyAll()
wait(); wait(long timeout);
wait(long timeout, int nanos)
18
The clone() method
• To create an object from an existing object
aCloneableObject.clone()
19
Clone example
public 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.
20
Clone example
Stack aStack = new Stack();
Stack anotherStack = aStack.clone();
Stack s = (Stack)super.clone();
s.items = (Vector)items.clone();
return s;
anotherStack
s
aStack
[Vector]
items
[Stack]
items
[Vector]
[Stack]
21
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.
22
More clone example
class 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();
CloneNotSupportedException
}
is thrown at runtime.
}
23
More clone example
class 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 class CloneDemo3 {
public int getx() {
public static void main(String args[])
return x;
throws CloneNotSupportedException {
}
A obj1 = new A(37);
}
A obj2 = (A)obj1.clone();
System.out.println(obj2.getx());
}
}
success!
24
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.
25
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);
}
26
The equals() method
aStack.equals(anotherStack);
// for final class
public boolean equals(Object obj) {
if (this == obj)
There are cases that:
return true;
x.equals(y)  true
if (!(obj instanceof Stack)) y.equals(x)  false
or vice versa
return false;
Stack that = (Stack) obj;
return (that.items.equals(items);
}
27
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() { . . . }
28