CS 151: Object-Oriented Design November 12 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak www.cs.sjsu.edu/~mak.

Slides:



Advertisements
Similar presentations
Lecture 5: Interfaces.
Advertisements

Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Identity and Equality Based on material by Michael Ernst, University of Washington.
Inheritance Lakshmish Ramaswamy. Example A Rectangle class with area method A Circle class with area method Array containing references to circles & rectangles.
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.
1 Class Design CS 3331 Fall Outline  Organizing classes  Design guidelines  Canonical forms of classes equals method hashCode method.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
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 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
CS2200 Software Development Lecture: Object class A. O’Riordan, 2008.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
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.
Java Syntax Primitive data types Operators Control statements.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
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.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
CS 46B: Introduction to Data Structures June 4 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Inheritance Part II. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
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.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Java Implementation: Part 3 Software Construction Lecture 8.
Lecture 2 Object Oriented Programming Basics of Java Language MBY.
Lecture # 8 Constructors Overloading. Topics We will discuss the following main topics: – Static Class Members – Overloaded Methods – Overloaded Constructors.
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.
Polymorphism. 3 main programming mechanisms that constitute OOP: 1. Encapsulation 2. Inheritance 3. Polymorphism.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Java Type System and Object Model Horstmann ch , 7.7.
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,
CS 152: Programming Language Paradigms April 21 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.
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.
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.
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.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
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.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and Polymorphism.
Polymorphism 1. Reuse of code: every time a new sub-class is defined, programmers are reusing the code in a super-class. All non-private members of a.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Chapter 7: Cloning and RTTI
Object-oriented Programming in Java
CSC 205 Java Programming II
Computer Science II Exam 1 Review.
Overloading and Constructors
Extending Classes.
Chapter 8 Class Inheritance and Interfaces
Review for Midterm 3.
Chapter 7 Java Object Model
Presentation transcript:

CS 151: Object-Oriented Design November 12 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak

SJSU Dept. of Computer Science Fall 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. 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: mQy_Ajpa9IdobfNZmM/viewform mQy_Ajpa9IdobfNZmM/viewform

SJSU Dept. of Computer Science Fall 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 Science Fall 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 Science Fall 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 Science Fall 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 Science Fall 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 Science Fall 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 Science Fall 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 Science Fall 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 Science Fall 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 Science Fall 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 Science Fall 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 Science Fall 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 Science Fall 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 Science Fall 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 Science Fall 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 Science Fall 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 Science Fall 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 Science Fall 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 public boolean equals(Object other) { if (!super.equals(other)) return false; Manager otherManager = (Manager) other; return bonus == otherManager.bonus; }... }

SJSU Dept. of Computer Science Fall 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 Science Fall 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 Science Fall 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 = x y : Employee name = “Smith” salary = : Employee name = “Smith” salary = x y

SJSU Dept. of Computer Science Fall 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 Science Fall 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 are immutable, so a shallow copy of the name is OK. But changing the hire date of one copy will change the hire date of the other copy.

SJSU Dept. of Computer Science Fall 2013: November 12 CS 151: Object-Oriented Design © R. Mak 26 Cloning Make a deep copy of the hire date.

SJSU Dept. of Computer Science Fall 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 Science Fall 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 Science Fall 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!");