170 likes | 261 Views
CompSci 230 Software Construction. Java Implementation: Part 3 Version 1.1 of 2014-03-18: added learning objectives . Agenda. Topics: Enum Types M emory allocation: another view of Java’s type system Object Identity, Assignment, Equality, and Copying The Object class
E N D
CompSci 230Software Construction Java Implementation: Part 3 Version 1.1 of 2014-03-18: added learning objectives
Agenda • Topics: • Enum Types • Memory allocation: another view of Java’s type system • Object Identity, Assignment, Equality, and Copying • The Object class • Overriding equals()and toString() • Cloning • Nested Classes • What and Why • Reading, in The Java Tutorials: • Enum Types and Nested Classespages, in the Classes and Objects Lesson. • Object as a Superclass page, in the Interface and Inheritance Lesson. • Equality, Relational, and Conditional Operators page, in the Language Basics Lesson. • For reference: • The 3 things you should know about hashCode(), Eclipse Source Developer, available 20 March 2013.
Learning objectives for this week • Students will be competent at implementing OO designs in Java • Today: Interfaces, reference data types, abstract classes, intro to generics • Wednesday: Visibility, packages, static & dynamic typing, conversion & casting • Friday: Enums, memory allocation, object identity & assignment & equality & cloning, nested classes • The lectures will give you the basic “theory”, but they won’t give you a “working understanding” – you have to do the hard-yards of putting these ideas into practice. • You won’t even understand the theory, if you listen passively to lectures. I’ll try to help you “learn how to learn” from the Java tutorials. • You’ll get many chances to develop your understanding in your lab assignments for this course.
Enum Types public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } • “An enum type is a special data type that enables for a variable to be a set of predefined constants. • The variable must be equal to one of the values that have been predefined for it. • Common examples include • compass directions (values of NORTH, SOUTH, EAST, and WEST) and • the days of the week. • “Because they are constants, the names of an enum type's fields are in uppercase letters. • “… define an enum type by using the enum keyword. • For example, you would specify a days-of-the-week enum type as: • “You should use enum types any time you need to represent a fixed set of constants. • That includes natural enum types such as the planets in our solar system and • data sets where you know all possible values at compile time—for example, • the choices on a menu, • command line flags, and so on.”
int i = 20; Ball b1 = new Ball( 10, i, Color.RED ); Memory Allocation Object o1 = b1; static type dynamic type pointsTo pointsTo • We use a reference variable to refer to instantiated objects. • The value in a reference variable is, essentially, a pointer to an object. • A special value (null) indicates that there is no object. • The runtime system (the JVM) interprets reference values as an index into a heap – an area of memory that is set aside, by the JVM, for storing instantiated objects. • Formally: the range of allowable values for a reference variable is defined by its reference type. This is a static property. • The reference type of o1 is Object. This means it can point to any instance of Object, or to any instance of any subclass of Object. • The new operator allocates sufficient memory on the heap to store all the fields of the object it is instantiating.
A model of Java’s type system (for reference) Source: Kollman, R. and Gogolla, M., “Capturing Dynamic Program Behaviour with UML Collaboration Diagrams”, Proc. CSMR, 2001.
Variables, revisited “The Java programming language defines the following kinds of variables: … ” [Variablespage of the Language BasicsLesson]
Object Identity pointsTo pointsTo Ball b1 = new Ball( 10, 20, Color.RED ); Object o1 = b1; true false System.out.println( o1 == b1 ); System.out.println( (String) o1==b1 ); pointsTo • If two reference variables have the same value, they are pointing to the same object. • This relationship is called “object identity”. • You can test it with the == operator.
Equality test: object identity System.out.println( (3+4) == 7 ); System.out.println( new Integer(3+4) == new Integer(7) ); true false true true System.out.println( (new Integer(3+4)).equals(new Integer(7)) ); System.out.println( (new Integer(7)).equals(3+4) ); System.out.println( (3+4).equals(new Integer(7)) ); System.out.println( ((Integer)(3+4)).equals(new Integer(7)) ); true • A box that contains 7 items is not identical to any other box that contains 7 items. • But… we would say “3 + 4 equals 7”. • If we want to know whether two boxes are equivalent (= have the same value), we might have to open up the boxes and look inside. • The equals() method is implemented as == in Object. • You should override equals(), if you define a subclass in which the “natural definition” for equality differs from the equals() it inherits.
Object The hashCode()Method … • “TheObject class, in the java.lang package, sits at the top of the class hierarchy tree. • Every class is a descendant, direct or indirect, of the Object class. • Every class you use or write inherits the instance methods of Object. • You need not use any of these methods, but, if you choose to do so, you may need to override them with code that is specific to your class. • “The value returned by hashCode() is the object's hash code, which is the object's memory address in hexadecimal. • “By definition, if two objects are equal, their hash code must also be equal. • If you override the equals() method, you change the way two objects are equated and Object's implementation of hashCode() is no longer valid. • Therefore, if you override the equals()method, you must also override the hashCode() method as well.” • The hashCode() method returns an int. • Hashcodes are used in HashSet, HashMap, and some other Collection classes which use a hashing algorithm. • These classes will give incorrect results, if equal instances in a Collection have different hashcodes. • They will have poor performance, if many unequal instances share the same hashcode.
String Equality – be careful… String s1 = "Apple"; String s2 = "Apple"; System.out.println("s1==s2:" + (s1==s2)); System.out.println("s1.equals(s2):" + s1.equals(s2)); True True String s3 = new String("Apple"); String s4 = new String("Apple"); System.out.println("s3==s4:" + (s3==s4)); System.out.println("s3.equals(s4):" + s3.equals(s4)); False True • Strings are immutable. • None of the String methods will modify the value of an existing instance; instead, a new String instance is created, and returned. • Some strings are “interned” (= accessible by a hash lookup, at runtime). • You may get a reference to an existing String instance when you ask for a new String. Then again, you might not… • Moral: you should use equals(), and not ==, to test Strings for equality.
Other Overridable Object Methods public class Object { ... public boolean equals(Object obj) { return (this == obj); } public String toString() { return getClass().getName() ... } protected Object clone() throws CloneNotSupportedException { ... } } • Object has two other methods you might want to override • toString(): returns a String representation of the object • clone(): create a copy of an existing object
The getClass() method public class Object { ... // Returns the runtime class of an object public final Class getClass() { ... } ... } Point p1 = new Point(10, 20); Class c = p1.getClass (); System.out.println(c.getName()); System.out.println(c.getSuperclass().getName()); Point java.lang.Object • You cannot override getClass(). • Can you see why this isn’t allowed?
Cloning • The clone() method in the Object class • Throws an exception, if the class of this object does not implement the interface Cloneable • Creates an object of the same type as the original object • Initialises the clone’s instance variables to the same values as the original object's instance variables • This is a shallow copy: any objects that are referenced by instance variables will not be cloned. • If an object references another object, then you might want to override clone() so that • It always throws an exception (i.e. is uncloneable), or • It clones the other object, and references it from the clone of the original -- so that the clone of the original can be modified or destroyed without affecting the original.
Nested Classes public class MyRegularClass { ... } Outer class class MyInnerClass { ... } Inner class • Definition: A class defined inside another class. • Motivation: Some classes only make sense in the context of another enclosing class. Examples: • An Enumeration or Iterator object cannot exist by itself. It makes sense only in association with a collection being enumerated/iterated. • A GUI event handler cannot exist by itself. It makes sense only in association with the GUI component for which it handles events. • Reference: the Writing an Event Listener Lesson of the Java Tutorials. • Nested classes define, and enforce, a composition relationship between the outer class and its inner classes:
Nested Classes: Some Details • “A nested class is a member of its enclosing class. • Non-staticnested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. • Staticnested classes do not have access to other members of the enclosing class. • “As a member of [its outer class], a nested class can be declared private, public, protected, or package private. • (Recall that outer classes can only be declared public or package private.)” • “There are two additional types of inner classes. • You can declare an inner class within the body of a method. • Such a class is known as a local inner class. • You can also declare an inner class within the body of a method without naming it. • These classes are known as anonymous inner classes. • You will encounter such classes in advanced Java programming.”
Review • Topics: • Enum Types • Memory allocation: another view of Java’s type system • Object Identity, Assignment, Equality, and Copying • The Object class • Overriding equals() and toString() • Cloning • Nested Classes • What and Why • End of Theme A: The OO Programming Paradigm • We took a top-down approach: use-case analysis class design implementation.