CS 151: Object-Oriented Design November 12 Class Meeting Department of Computer Science San Jose...
-
Upload
corey-doyle -
Category
Documents
-
view
219 -
download
0
description
Transcript of CS 151: Object-Oriented Design November 12 Class Meeting Department of Computer Science San Jose...
CS 151: Object-Oriented Design November 12 Class Meeting
Department of Computer ScienceSan Jose State University
Fall 2013Instructor: Ron Mak
www.cs.sjsu.edu/~mak
SJSU Dept. of Computer ScienceFall 2013: November 12
CS 151: Object-Oriented Design© R. Mak
2
Student Volunteer Opportunity Student help needed at the professional Cleantech Open Global
Forum conference, Nov. 19, 20, and 21 at the San Jose Convention Center. http://www2.cleantechopen.org/ This conference showcases 150 of the year’s biggest game changing
technologies in the fields of energy, chemical and advanced materials, information and communications, transportation, and more.
Learn from experts and network with professionals.
Cleantech Open is a not-for-profit organization dedicated to finding, funding, and fostering the brightest cleantech startups on the planet. More than 150 of the world’s best entrepreneurs participate in its mentoring, education, and support programs.
This would be a great opportunity for students to network with professionals in the cleantech industry.
To volunteer, register at:https://docs.google.com/forms/d/1ChuX8ivhKAsmzM8VskFWkPibnmQy_Ajpa9IdobfNZmM/viewform
SJSU Dept. of Computer ScienceFall 2013: November 12
CS 151: Object-Oriented Design© R. Mak
3
Data Types In a programming language, what is a data type?:
A set of values Example: integer values, real values, String values
A set of legal operations that can be performed on the values. Example: integer + - * / Example: String length, substring, concatenation, truncation
What can have types? data values literals variables procedure and function parameters function return values
SJSU Dept. of Computer ScienceFall 2013: November 12
CS 151: Object-Oriented Design© R. Mak
4
Data Types Every type in Java is either:
A primitive type int, short, long, byte, char, float, double, boolean
A class type An interface type An array type The null type
Yes, null is a type. Its only value is null.
A Java value is either: A value of a primitive type A reference to an object of a class A reference to an array null
SJSU Dept. of Computer ScienceFall 2013: November 12
CS 151: Object-Oriented Design© R. Mak
5
Data Types The following can have an interface type:
Variables Method parameters and return values
You cannot have a value of an interface type!
void is not a type. It’s just a keyword to indicate that a method
does not return a value._
SJSU Dept. of Computer ScienceFall 2013: November 12
CS 151: Object-Oriented Design© R. Mak
6
Strongly Typed Language In a strongly typed language, each variable has a type.
The compiler can perform static type checking.
Advantages of static type checking include: Catch more errors during translation. Improve program security and reliability. Improve program readability. Remove ambiguities. Verify interface consistency and correctness. Greater programmer discipline. Generate more efficient object code.
Java is a strongly typed language.
SJSU Dept. of Computer ScienceFall 2013: November 12
CS 151: Object-Oriented Design© R. Mak
7
Type Compatibility If type A is assignment compatible with type B, then:
A value of type A can be assigned to a variable of type B. Examples:
Type int is assignment compatible with type float. You can assign an int value to a float variable.
Type int is not assignment compatible with type String. You cannot assign an int value to a String variable.
A value of type A can be passed by value to a parameter of type B.
Type A is comparison compatible with type B if a type A value can be compared to a type B value. Example: With some languages, strings of different lengths are
comparison compatible. The shorter string is padded at the end with blanks at run time before the comparison is made.
SJSU Dept. of Computer ScienceFall 2013: November 12
CS 151: Object-Oriented Design© R. Mak
8
Subtypes A subtype represents a subset of the values
of its supertype. The subtype inherits the operations of the supertype.
_
SJSU Dept. of Computer ScienceFall 2013: November 12
CS 151: Object-Oriented Design© R. Mak
9
Subtypes When is S a subtype of T?
S and T are the same type. S and T are both class types,
and T is a direct or indirect superclass of S. S is a class type, T is an interface type,
and S or one of its superclasses implements T. S and T are both interface types,
and T is a direct or indirect superinterface of S. S and T are both array types, and the component type of S
is a subtype of the component type of T. S is not a primitive type and T is the type Object. S is an array type and T is Cloneable or Serializable. S is the null type and T is not a primitive type.
SJSU Dept. of Computer ScienceFall 2013: November 12
CS 151: Object-Oriented Design© R. Mak
10
Subtypes Verify that:
Container is a subtype of Component.
JButton is a subtype of Component.
ListIterator is a subtype of Iterator.
FlowLayout is a subtype of LayoutManager.
JButton[] is a subtype of Component[].
int[] is a subtype of Object. But not of Object[].
SJSU Dept. of Computer ScienceFall 2013: November 12
CS 151: Object-Oriented Design© R. Mak
11
Enumerated Types An enumerated type has a finite set of values.
Often the set contains a very small number of values. Example: Type Size has three values: SMALL, MEDIUM, and
LARGE
The traditional way to implement Size and its values:
But then compiler cannot check for type errors. Example:
public static final int SMALL = 1;public static final int MEDIUM = 2;public static final int LARGE = 3;
int size = LARGE;size++;
SJSU Dept. of Computer ScienceFall 2013: November 12
CS 151: Object-Oriented Design© R. Mak
12
Enumerated Types Use an enumerated type instead:
Equivalent to:
Each enumeration value is an object of class Size._
public enum Size { SMALL, MEDIUM, LARGE };
public class Size{ private Size() {} public static final Size SMALL = new Size(); public static final Size MEDIUM = new Size(); public static final Size LARGE = new Size();}
Why is the constructor private?
SJSU Dept. of Computer ScienceFall 2013: November 12
CS 151: Object-Oriented Design© R. Mak
13
Enumerated Types An enumerated type can have a constructor,
fields, and methods:public enum Size{ private double value;
// Private constructor private Size(double value) { this.value = value; }
public double getValue() { return value; }
// Enumeration values SMALL(0.5), MEDIUM(1), LARGE(2)}
SJSU Dept. of Computer ScienceFall 2013: November 12
CS 151: Object-Oriented Design© R. Mak
14
The instanceof Operator The instanceof operator allows you to guarantee
that a type cast will succeed.
But do we know exactly what is the type of the value of x? It can be Shape or any subclass of Shape.
_
Object x = ...;
if (x instanceof Shape) { Shape s = (Shape) x; ...}
SJSU Dept. of Computer ScienceFall 2013: November 12
CS 151: Object-Oriented Design© R. Mak
15
Type Inquiry For any object reference, you can find
the exact type of the object:
The Class object is a type descriptor.
Among the information that the Class object contains: Type name Type superclass
Test if variable x refers to an object that is exactly the Rectangle class.
Class c = x.getClass();
String name = obj.getClass().getName();
if (x.getClass() == Rectangle.class) ...
SJSU Dept. of Computer ScienceFall 2013: November 12
CS 151: Object-Oriented Design© R. Mak
16
The Object Class All Java classes are subclasses of the Object class.
Object is the ultimate root of every class hierarchy.
All classes inherit the following Object methods:
String toString() returns a string representation of an object.
boolean equals(Object other) compares an object to another object.
int hashCode() returns a object’s hash code.
Object clone() returns a copy of the object._
SJSU Dept. of Computer ScienceFall 2013: November 12
CS 151: Object-Oriented Design© R. Mak
17
Method toString() An object’s toString() method is automatically called
whenever:
You concatenate an object with a string. Example:
is executed as if you had written:
You print an object with print() or println()._
Rectangle rect = new Rectangle(10, 20, 30, 40);String str = "rect = " + rect;
String str = "rect = " + rect.toString();
SJSU Dept. of Computer ScienceFall 2013: November 12
CS 151: Object-Oriented Design© R. Mak
18
Method toString() You should override the default toString() method
in your own classes. If your class has a superclass, first call its toString() method.
Example output:
public class Employee{ public String toString() { return getClass().getName() + "[name=" + name + ",salary=" + salary + "]"; } ...}
public class Manager extends Employee{ public String toString() { return super.toString() + "[bonus=" + bonus + "]"; } ...}
Manager[name=Mary Jane,salary=100000][bonus=25000]
SJSU Dept. of Computer ScienceFall 2013: November 12
CS 151: Object-Oriented Design© R. Mak
19
Equality Testing If x and y are references to objects, the test x == y
tests whether x and y refer to the identical object.
The test x.equals(y) tests whether x and y refer to objects that may be distinct but have “equal” contents.
By default, method equals() tests for identity:public class Object{ public boolean equals(Object other) { return this == other; } ...}
SJSU Dept. of Computer ScienceFall 2013: November 12
CS 151: Object-Oriented Design© R. Mak
20
Equality Testing Your class should override the equals() method
in an application-specific way. You can compare the objects’ corresponding fields. First check for identity.
No point in doing a field-by-field comparison if the two objects are identical.
If your class has a superclass, first call its equals() method.public class Manager extends Employee{ @Override public boolean equals(Object other) { if (!super.equals(other)) return false;
Manager otherManager = (Manager) other; return bonus == otherManager.bonus; } ...}
SJSU Dept. of Computer ScienceFall 2013: November 12
CS 151: Object-Oriented Design© R. Mak
21
Equality Testing Any equals() method must be:
Reflexive For any reference value x, x.equals(x) must be true.
Symmetric For any reference values x and y,
x.equals(y) is true if and only if y.equals(x) is true.
Transitive For any reference values x, y, and z,
if x.equals(y) is true and y.equals(z) is true,then x.equals(z) must be true._
SJSU Dept. of Computer ScienceFall 2013: November 12
CS 151: Object-Oriented Design© R. Mak
22
Hash Code Every Java object has a “built-in” hash code
which is returned by method hashCode(). If x.equals(y) then x.hashCode() == y.hashCode() In other words, the hash code is based on an object’s contents.
Compute the hash codes of the individual fields of an object and combine them. Multiply the individual hash codes by relatively prime numbers
before adding them together.public class Employee{ public int hashCode() { return 11*name.hashCode() + 13*(new Double(salary)).hashCode(); } ...}
SJSU Dept. of Computer ScienceFall 2013: November 12
CS 151: Object-Oriented Design© R. Mak
23
Cloning If x is a reference to an object, then y = x
makes y a reference to the same object. This is a shallow copy.
A deep copy makes a new object with equal contents.
: Employee
name = “Smith”salary = 75000
x
y
: Employee
name = “Smith”salary = 75000
: Employee
name = “Smith”salary = 75000
x
y
SJSU Dept. of Computer ScienceFall 2013: November 12
CS 151: Object-Oriented Design© R. Mak
24
Cloning In order for an object to be cloneable, its class must be
tagged with the marker interface Cloneable. Remember that a marker interface declares no methods.
public class Employee implements Cloneable{ public Employee clone() { try { return (Employee) super.clone(); } catch (CloneNotSupportedException ex) { return null; // should never happen } } ...}
Call the Object class’s clone() method.
SJSU Dept. of Computer ScienceFall 2013: November 12
CS 151: Object-Oriented Design© R. Mak
25
Cloning Cloning can be tricky and error-prone.
Be sure you know which fields of an object to deep-copy and which fields to shallow-copy.
Strings areimmutable,so a shallowcopy of thename is OK.
But changing thehire date of one copy will change the hire date of the other copy.
SJSU Dept. of Computer ScienceFall 2013: November 12
CS 151: Object-Oriented Design© R. Mak
26
Cloning
Make a deep copyof the hire date.
SJSU Dept. of Computer ScienceFall 2013: November 12
CS 151: Object-Oriented Design© R. Mak
27
Reflection Reflection is a mechanism that allows a program
to inspect its objects at run time to obtain metadata about the objects. A program can manipulate the “internals” of an object
without knowing (at compile time) the type of the object.
Classes that support reflection: Class Package Field Method Constructor Array
SJSU Dept. of Computer ScienceFall 2013: November 12
CS 151: Object-Oriented Design© R. Mak
28
Inspecting a Class A Class object provides information about a class:
Its superclass All the interfaces that it implements
Example:
Its package The names and types of all its fields The names, parameter types, and return types of all its methods
Example: Get a Method object for contains(int x, int y)
The parameter types of all its constructors
Class interfaces[] = Rectangle.class.getInterfaces();
Method m = Rectangle.class.getDeclaredMethod("contains", int.class, int.class);
SJSU Dept. of Computer ScienceFall 2013: November 12
CS 151: Object-Oriented Design© R. Mak
29
Inspecting a Class You can call a method from the Method object.
Dynamic method invocation is useful to call a method that is not known when the program is compiled.
Example: Call Math.sqrt(4.0)
The first argument of invoke() is the implicit object reference of the call.
Make it null to call a static method. Combine dynamic class loading with dynamic method
invocation if the ultimate in flexibility is required.
Method m = Math.class.getDeclaredMethod("sqrt", double.class);double r = (Double) m.invoke(null, 4.0);
Method m = PrintStream.class.getDeclaredMethod("println", String.class);m.invoke(System.out, "Hello, world!");