Java Type System and Object Model Horstmann ch.7.1-7.5, 7.7.

Slides:



Advertisements
Similar presentations
 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
Advertisements

Identity and Equality Based on material by Michael Ernst, University of Washington.
Java Review Interface, Casting, Generics, Iterator.
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
Effective Java, Chapter 3: Methods Common to All Objects.
Generic programming in Java
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 17 – Generic Programming.
1 Class Design CS 3331 Fall Outline  Organizing classes  Design guidelines  Canonical forms of classes equals method hashCode method.
Effective Java, Chapter 3: Methods Common to All Objects Paul Ammann.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
1 More on Inheritance Overview l Object: The father of all classes l Casting and Classes l Object Cloning l Importance of Cloning.
CS2200 Software Development Lecture: Object class A. O’Riordan, 2008.
1 Java Object Model Part 1. 2 Type Definition: set of values – a set of values and set of operations –a set of operations that can be applied to those.
1 Java Object Model Part 2: the Object class. 2 Object class Superclass for all Java classes Any class without explicit extends clause is a direct subclass.
Inheritance and interfaces A class C1 is derived from class C2, then C1 is called subclass, and C2 is called superclass Superclass-parent, base class Subclass.
March 2005Java Programming1. March 2005Java Programming2 Why Java? Platform independence Object Oriented design Run-time checks (fewer bugs) Exception.
Comparing Objects in Java. The == operator When you define an object, for instance Person p = new Person("John", 23); we talk about p as if its value.
GETTING INPUT Simple I/O. Simple Input Scanner scan = new Scanner(System.in); System.out.println("Enter your name"); String name = scan.nextLine(); System.out.println("Enter.
Chapter 11 Abstract Classes and Interfaces 1. Abstract method New modifier for class and method: abstract An abstract method has no body Compare: abstract.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Announcements  I will discuss the labtest and the written test #2 common mistakes, solution, etc. in the next class  not today as I am still waiting.
Java Implementation: Part 3 Software Construction Lecture 8.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Puzzle 3 1  Write the class Enigma, which extends Object, so that the following program prints false: public class Conundrum { public static void main(String[]
Non-static classes Part 2 1. Methods  like constructors, all non-static methods have an implicit parameter named this  for methods, this refers to the.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators.
 Definition: Accessing child class methods through a parent object  Example: Child class overrides default parent class methods  Example: Child class.
Types in programming languages1 What are types, and why do we need them?
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Effective Java: Methods Common to All Objects SWE 619: Fall 2008 Paul Ammann.
Parametric Polymorphism and Java Generics. Announcements One day extension on HW5 Because of an error in my HW5 config HW6 out, due November 10 Grades.
Lecture 4: Extending Classes. Concept Inheritance: you can create new classes that are built on existing classes. Through the way of inheritance, you.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
1 Class Design CS 3331 Sec 6.1 & 6.3 of [Jia03]. 2 Outline  Organizing classes  Design guidelines  Canonical forms of classes equals method hashCode.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
The Prototype Pattern (Creational) ©SoftMoore ConsultingSlide 1.
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
CS 151: Object-Oriented Design November 12 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
FEN 2014UCN Teknologi/act2learn1 Object-Oriented Programming “ The Three Pillars of OOP”: Encapsulation Inheritance Polymorphism The Substitution Principle.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
CSC142 NN 1 CSC 142 Overriding methods from the Object class: equals, toString.
Classes Revisited Chapter 8.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
1 clone() Defined in Object Creates an identical copy –Copies pointers to fields (does not copy fields of fields) –Makes a shallow copy if the object’s.
More on Objects Static and equals.. Each object takes memory Each time you make an object of a given class – you create a space in memory. E.g. public.
Object-oriented Programming in Java
CS 302 Week 11 Jim Williams, PhD.
Non-static classes.
Computer Science II Exam 1 Review.
null, true, and false are also reserved.
Extending Classes.
Effective Java, Chapter 3, 3rd Edition: Methods Common to All Objects
Overriding methods from the Object class: equals, toString
CS/ENGRD 2110 Spring 2019 Lecture 6: Consequence of type, casting; function equals
Review for Midterm 3.
Chapter 7 Java Object Model
CS 240 – Advanced Programming Concepts
Presentation transcript:

Java Type System and Object Model Horstmann ch , 7.7

QUIZ static/dynamic type Which – if any – errors arise? Employee e = null; a) e.clear(); b) e.setSalary(1000); No errorCompiler error Exception on runtime 1.a),b) 2.a)b) 3.a)b) 4.b)a) 5.a),b) 6.a)b) 7.b)a) 8.b)a) 9.a),b) 10. I don’t know

Types Non-primitive types Primitive types Enum types Object Equals Clone Generics

Nonprimitive types typeobject class types Rectangle String new Rectangle(2,4,8,8) "dProg2" interface types Shape Comparable array types int[][] String[] new int[3][7] {"dIntProg","dProg2"} no objects of interface type! typevalue null type null

Non-primitive type: variables Variables of non-primitive type contains reference to object of same type Vehicle b; b = new Vehicle(); or of a sub type Vehicle c; c = New Automobile(); Vehicle d; d = new HorseCart();

Subtype Relationship T1 is subtype of T2, T1 T2 –if T1 is the same type as T2 –or T1 implements T2 –or T1 extends T2 –or there is T3 such that T1 T3 and T3 T2 –or T1 is T3[], T2 is T4[] and T3 T4 –or T1 is array type and T2 is Cloneable or Serializable –or T1 is non-primitive and T2 is Object –or T1 is null type and T2 is non-primitive

Subtype Examples Container is a subtype of Component JButton is a subtype of Component FlowLayout is a subtype of LayoutManager ListIterator is a subtype of Iterator Rectangle[] is a subtype of Shape[] Iterator is a subtype of Object

QUIZ 1 Comparable is a subtype of Object ? 2 Comparable is a subtype of String ? 3 String is a subtype of Comparable ? 4 int[] is a subtype of Object ? 5 int[] is a subtype of Object[] ? 6 Serializable[] is a subtype of Object[] ? 7 int[][] is a subtype of Serializable[] ? Yes/No

Type check: compile time Static versus dynamic type Vehicle v; v = new Automobile(); Object obj; obj = v; Compiler looks at static type only Automobile bmw bmw = v; Use type cast bmw = (Automobile) v; Compiler is happy! compile time error Static type of v is Vehicle Dynamic type of v is Automobile Static type of (Automobile)v is Automobile

Type check: runtime You may fool the compiler: Vehicle v = new HorseCart(); Automobile bmw = (Automobile) v; Compiler is happy But at runtime Static type of (Automobile)v is Automobile Exception in thread "main“ java.lang.ClassCastException: HorseCart cannot be cast to Automobile Dynamic type of v is HorseCart

QUIZ static/dynamic type Which – if any – errors arise? Employee e = new Driver(); a) e.setBonus(10); b)((Manager)e).setBonus(10); No errorCompiler error Exception on runtime 1.a),b) 2.a)b) 3.a)b) 4.b)a) 5.a),b) 6.a)b) 7.b)a) 8.b)a) 9.a),b) 10. I don’t know

Type Inquiry Test subtype: if (bmw instanceof Vehicle)... Common before casts: Vehicle fourWheeler = (Vehicle) bmw; Test exact type: if (bmw.getClass() == Vehicle.class) true if dynamic type of bmw is subtype of Vehicle true if dynamic type of bmw is Vehicle and not a subtype

QUIZ subtype What is written? Employee e = new Manager(); System.out.println( (e instanceof Comparable) +” ”+ (e instanceof Manager) +” ”+ e.getClass().getName() ); 1.true Employee 2.true Manager 3.truefalseEmployee 4.truefalseManager 5.falsetrueEmployee 6.falsetrueManager 7.false Employee 8.false Manager 9. I don’t know

Types Non-primitive types Primitive types Enum types Object Equals Clone Generics

Primitive types Typevalue int boolean char double true 'k' 4.567E-3...

Primitive type: variables Variable of primitive type contains value of same type int k = 4; boolean good = false; Widening –In assignment, a widening conversion ( char → int → double ) is automatic double a = 3; Narrowing –Conversion in the other direction (narrowing) requires a cast int n = (int) 5.7; 5 n 3.0 a 4 k false good

Wrapper Classes Primitive types aren't classes Use wrappers when objects are expected Wrapper for each type: Integer Short Long Byte Character Float Double Boolean Example: ArrayList ArrayList numbers = new ArrayList (); AutoboxingShorthand for numbers.add(13);numbers.add(new Integer(13)); int n = numbers.get(0);int n = (numbers.get(0)).intValue();

QUIZ primitive types What is written? int n1 = 5/2; double n2 = 5/2; double n3 = (double)5/2; System.out.println( n1 +” ”+ n2 +” ”+ n3 ); I don’t know

Types Non-primitive types Primitive types Enum types Object Equals Clone Generics

Enumerated Types Finite set of values –Example: { SMALL, MEDIUM, LARGE } Modelled by class with fixed number of instances public enum Size { SMALL, MEDIUM, LARGE }; –is equivalent to 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(); } –Private constructor! Typical use: Size imageSize = Size.MEDIUM; if (imageSize == Size.SMALL)...

Types Non-primitive types Primitive types Enum types Object Equals Clone Generics

Object : The Cosmic Superclass All classes extend Object Selected methods: String toString() boolean equals(Object obj) Object clone() Class getClass() int hashCode()

Types Non-primitive types Primitive types Enum types Object Equals Clone Generics

equals(…) a == b is false a.equals(b) false, if equals inherited from Object maybe true, if equals is overridden

Overriding equals(…) public Class Vehicle { private int noOfWheels; private String name; … public boolean equals(Object obj) { ? }

Overriding equals(…) public Class Vehicle { private int noOfWheels; private String name; … public boolean equals(Object obj) { if (obj instanceof Vehicle) { Vehicle other = (Vehicle) obj; return (noOfWheels == other.noOfWheels) && name.equals(other.name); } else return false; }

equals(…) and inheritance public Class Automobile extends Vehicle { private PowerSource power; … public boolean equals(Object obj) { ? }

equals(…) and inheritance public Class Automobile extends Vehicle { private PowerSource power; … public boolean equals(Object obj) { if (obj instanceof Automobile) { Automobile other = (Automobile) obj; return super.equals(other) && power.equals(other.power); } else return false; }

equals(…) and inheritance Asymmetry: –X.equals(Y) returns true –Y.equals(X) returns false

Requirements for equals Method equals must be equivalence relation reflexive: x.equals(x) symmetric: x.equals(y) if and only if y.equals(x) transitive: if x.equals(y) and y.equals(z), then x.equals(z) x.equals(null) must return false

perfect equals(…) public Class Vehicle { private int noOfWheels; private String name; … public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Vehicle obj = (Vehicle) obj; return (noOfWheels == other.noOfWheels) && name.equals(other.name); }

equals(…) and hashing hashCode method used in HashMap, HashSet Computes an int from an object Example: hash code of String int h = 0; for (int i = 0; i < s.length(); i++) h = 31 * h + s.charAt(i); Hash code of "eat" is Hash code of "tea" is

equals(…) and hashing Must be compatible with equals: if x.equals(y), then x.hashCode() == y.hashCode() Object.hashCode hashes memory address NOT compatible with redefined equals Remedy: Hash all fields and combine codes: public class Vehicle { public int hashCode() { return 11 * name.hashCode() + 13 * new Double(noOfWheels).hashCode(); }... }

QUIZ clone/equals What output should we expect? MyClass x = new MyClass(); MyClass y = x.clone(); System.out.println( x.equals(y) +” ”+ (x == y) ); 1.true 2.truefalse 3.falsetrue 4.false 5. I don’t know

Types Non-primitive types Primitive types Enum types Object Equals Clone Generics

Shallow copy Assignment x = y;

Deep copy cloning x = y.clone();

Shallow cloning clone inherited from Object makes shallow cloning x = y.clone();

Deep cloning Override clone to make deep cloning x = y.clone();

Overriding clone() public Class Vehicle { private int noOfWheels; private PowerSource power; … public Vehicle clone() { Vehicle twin = (Vehicle) super.clone(); twin.power = power.clone(); return twin; } Shallow cloning Deep cloning Actually, the compiler won’t accept this

Overriding clone() Public class Object { protected Object clone() { … } } public Class Vehicle implements Cloneable { public Vehicle clone() { try { Vehicle twin = (Vehicle) super.clone(); twin.power = power.clone(); return twin; catch (CloneNotSupportedException e) { return null; } } Why so complicated ? Never happens

Overriding clone() Deep cloning ?

QUIZ deep/shallow copy How much does viggos account hold at end - in case of cloning being Customer viggo = new Customer( , new Account(1000) ); Customer twin = viggo.clone(); twin.getAccount().withdraw(200); Shallow?Deep? I don’t know

Types Non-primitive types Primitive types Enum types Object Equals Clone Generics

Generic Types A generic type has one or more type variables public class ArrayList { public E get(int i) {... } public E set(int i, E newValue) {... }... private E[] elementData; } Type variables are instantiated with non-primitive types ArrayList = new ArrayList (); Type variable E is declared NOTE: If S a subtype of T, ArrayList is not a subtype of ArrayList. int is primitive

Generic Methods A generic method in an ordinary (non-generic) class public class Utils { public static void fill( ArrayList a, E value, int count) { for (int i = 0; i < count; i++) a.add(value); } } Type parameters are inferred in call ArrayList ids = new ArrayList (); Utils.fill(ids, "default", 10); Type variable E is declared calls Utils. fill

Type Bounds The following method is limited: public static void append(ArrayList a, ArrayList b) { for (E elem : b) a.add(elem); } Cannot append an ArrayList to an ArrayList Overcome limitation with type bound: public static void append( ArrayList a, ArrayList b) { for (E elem : b) a.add(elem); } Declare 2 type variables E and F Make restriction: F is subtype of E

QUIZ generic type Is method correct? 1.No, compiler error 2.No, it compiles, but it is not correct 3.Yes, it compiles and it returns true precisely when value occurs in basket 4.I don’t know public > boolean search(F basket, E value) { for (E elem : basket) if (value.equals(elem)) return true; return false; }

Wildcards Overcome limitation with type bound: public static void append( ArrayList a, ArrayList b) { for (E elem : b) a.add(elem); } Definition of append never uses type F. Can simplify with wildcard: public static void append( ArrayList a, ArrayList b) { for (E elem : b) a.add(elem); }

Wildcards Typical example--start with public static > E getMax(ArrayList a) { E max = a.get(0); for (E elem : a) if (elem.compareTo(max) > 0) max = elem; return max; } E extends Comparable so that we can call compareTo Too restrictive--can't call with ArrayList Manager does not implement Comparable, only Comparable Wildcards to the rescue: public static > E getMax(ArrayList a)

QUIZ generic type/wildcard How would you expect the Collections.sort(…) method to be defined? 1. public static void sort(List a) {... } 2. public static > void sort(List a) {... } 3. public static > void sort(List a) {... } 4. public static > void sort(List a) {... } 5. public static void sort(List > a) {... } 6. I don’t know