280 likes | 450 Views
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.
E N D
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 public static void main(String[] args) { int x = 5; Point p = newPoint(2, 3); changeValue(x); changeReferenece(p); changeState(p); } After returning from changeReference, p is still Point of (2, 3) 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 changeState, p is changed to Point of (4, 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
Creating a package • Use a package statement at the top of the source file in which the class or the interface is defined. packagecom.chate.shapes; public class Oval { // . . . } packagecom.chate.shapes; public class Rectangle { // . . . } com └─── chate └─── shapes ├─── Oval.class └─── Rectangle.class classes in the same package are in the same directory/folder
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 (name@domain.com) • com.domain.name
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();
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. both packages have Rectangle.class • import java.awt.*; • import com.chate.shapes.*; • Rectangle r = new Rectangle(); // 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();
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
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).
Interface interfaceTurnable { voidturnLeft(); voidturnRight(); } • If a class want to be a Turnable, it must implement all methods defined in Turnable interface public class Car implements Turnable { . . . public voidturnLeft() { . . .} public voidturnRight() { . . . } }
Multiple interface inheritance interfaceTurnable { voidturnLeft(); voidturnRight(); } Vehicle <<interface>> Moveable <<interface>> Turnable interfaceMoveable { voidforward(); voidbackward(); } Car public class Car extends Vehicle implements Turnable, Moveable { // . . . public voidturnLeft() { . . . } public voidturnRight() { . . . } public voidforward() { . . . } public voidbackward() { . . . } }
Multiple interface inheritance interfaceTurnable { voidturnLeft(); voidturnRight(); } Vehicle <<interface>> Relocateable interfaceMoveable { voidforward(); voidbackward(); } <<interface>> Moveable <<interface>> Turnable Car public class Car extends Vehicle implements Turnable, Moveable { // . . . public voidturnLeft() { . . . } public voidturnRight() { . . . } public voidforward() { . . . } public voidbackward() { . . . } }
Multiple interface inheritance Vehicle <<interface>> Relocateable <<interface>> Moveable <<interface>> Turnable Car Human public class Human implements Turnable, Moveable { // . . . public voidturnLeft() { . . .} public voidturnRight() { . . . } public voidforward() { . . .} public voidbackward() { . . . } }
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(); {
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.
Method summary clone() equals(Object obj) hashcode() finalize() toString() getClass() notify() notifyAll() wait(); wait(long timeout); wait(long timeout, int nanos) Cannot override
The clone() method • To create an object from an existing object aCloneableObject.clone()
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.
aStack items [Stack] [Vector] Clone example Stack aStack = new Stack(); Stack anotherStack = aStack.clone(); Stack s = (Stack)super.clone(); s.items = (Vector)items.clone(); return s; anotherStack s [Vector] items [Stack]
More clone example class A{ private int x; public A(int i) { x = i; } } public class CloneDemo1 { public static void main(Stringargs[]) throws CloneNotSupportedException{ A obj1 = new A(37); A obj2 = (A)obj1.clone(); } } compile error: because Object.clone() is a protected method.
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.
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 int getx() { return x; } } success! 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()); } }
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.
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); }
The equals() method aStack.equals(anotherStack); // for final class public 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) true y.equals(x) false or vice versa
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 inthashCode() { . . . }