CS 46B: Introduction to Data Structures June 4 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak www.cs.sjsu.edu/~mak.

Slides:



Advertisements
Similar presentations
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Advertisements

Topic 5a – Interfaces Friends share all things. CISC370/Object Oriented Programming with Java.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
1 CS 171: Introduction to Computer Science II Review: OO, Inheritance, and Libraries Ymir Vigfusson.
1. 2 Introduction to Inheritance  Access Modifiers  Methods in Subclasses  Method Overriding  Converting Class Types  Why up-cast?  Why down-cast?
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
CS 106 Introduction to Computer Science I 11 / 28 / 2007 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 11 / 20 / 2006 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
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.
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.
Inheritance Part II. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
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[]
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
1 Abstract Class There are some situations in which it is useful to define base classes that are never instantiated. Such classes are called abstract classes.
CS 46B: Introduction to Data Structures July 7 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
CMSC 202 Inheritance II. Version 10/102 Inherited Constructors? An Employee constructor cannot be used to create HourlyEmployee objects. Why not? We must.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
CS 46B: Introduction to Data Structures June 25 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
Lecture 8: Object-Oriented Design. 8-2 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Objectives “Good object-oriented programming is really.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
CS 151: Object-Oriented Design September 26 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
CS 61B Data Structures and Programming Methodology July 3, 2008 David Sun.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
MIT AITI 2004 – Lecture 12 Inheritance. What is Inheritance?  In the real world: We inherit traits from our mother and father. We also inherit traits.
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…..
CS 61B Data Structures and Programming Methodology July 2, 2008 David Sun.
CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and.
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.
CS 146: Data Structures and Algorithms June 4 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
CMSC 202 Inheritance II. Version 10/092 Inherited Constructors? An Employee constructor cannot be used to create HourlyEmployee objects. Why not? We must.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Interfaces and Polymorphism CS 162 (Summer 2009).
CS 151: Object-Oriented Design November 12 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
CS 46B: Introduction to Data Structures June 30 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Inheritance ndex.html ndex.htmland “Java.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
CS 112 Programming 2 Lecture 06 Inheritance & Polymorphism (1)
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
CS 46B: Introduction to Data Structures July 23 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and Polymorphism.
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
Catie Welsh April 18,  Program 4 due Wed, April 27 th by 11:59pm  Final exam, comprehensive ◦ Friday, May 6th, 12pm  No class Friday - Holiday.
Lecture 12 Inheritance.
Chapter Goals To be able to declare and use interface types
Chapter 11 Inheritance and Polymorphism
Lecture 17: Polymorphism (Part II)
Continuing Chapter 11 Inheritance and Polymorphism
CS 302 Week 11 Jim Williams, PhD.
Introduction interface in Java is a blueprint of a class. It has static constants and abstract methods only. An interface is a way to describe what classes.
Building Java Programs
Inheritance Inheritance is a fundamental Object Oriented concept
Lecture 18: Polymorphism (Part II)
Chapter 11 Inheritance and Polymorphism Part 2
Chapter 11 Inheritance and Encapsulation and Polymorphism
CS 151: Object-Oriented Design October 8 Class Meeting
CS 240 – Advanced Programming Concepts
Presentation transcript:

CS 46B: Introduction to Data Structures June 4 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak The Ultimate Superclass  Class Object is the root of the Java class hierarchy. Any class that doesn’t explicitly extend a superclass implicitly extends class Object.  Object has two methods that you can override: String toString() boolean equals() 2

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak The toString() Method  A method of the Object class. Returns a string that describes an object.  Called automatically whenever: The object is printed. The object is part of a string concatenation.  The default toString() method returns a somewhat cryptic string. The string won’t tell you much about the object’s contents (i.e., values of its instance variables). 3

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak The toString() Method, cont’d 4 package notoverridden; public class Employee { private int id; private String lastName; private String firstName; private double salary; public Employee(int id, String lastName, String firstName, double salary) { this.id = id; this.lastName = lastName; this.firstName = firstName; this.salary = salary; }

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak The toString() Method, cont’d  What is printed? 5 package notoverridden; public class EmployeeTester { public static void main(String args[]) { Employee bob = new Employee(123, "Smith", "Robert", ); System.out.println("An employee is " + bob); } An employee is Default string returned by toString()

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak Override toString() 6 package overridden; public class Employee { private int id; private String lastName; private String firstName; private double salary; public Employee(int id, String lastName, String firstName, double salary) {... } public String toString() { return "Employee[id=" + id + "][lastName=" + lastName + "][firstName=" + firstName + "][salary=" + salary + "]"; } }

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak Override toString(), cont’d  What is printed? 7 package overridden; public class EmployeeTester1 { public static void main(String args[]) { Employee bob = new Employee(123, "Smith", "Robert", ); System.out.println("An employee is " + bob); } An employee is Employee[id=123][lastName=Smith][firstName=Robert][salary= ] String returned by the new improved toString()

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak toString() and Inheritance 8 package overridden; public class Manager extends Employee { private double bonus; public Manager(int id, String lastName, String firstName, double salary, double bonus) { super(id, lastName, firstName, salary); this.bonus = bonus; } public String toString() { return super.toString() + "[bonus=" + bonus + "]"; } }

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak toString() and Inheritance, cont’d  What is printed? 9 package overridden; public class EmployeeTester2 { public static void main(String args[]) { Employee bob = new Employee(123, "Smith", "Robert", ); Employee sue = new Manager(456, "Jones", "Susan", , ); System.out.println("An employee is " + bob); System.out.println("A manager is " + sue); } An employee is Employee[id=123][lastName=Smith][firstName=Robert][salary= ] A manager is Employee[id=456][lastName=Jones][firstName=Susan][salary= ][bonus=5000.0]

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak Take Roll 10

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak The equals() Method  A method of the Object class. Returns true or false depending on whether to objects are “equal” – i.e., have the same contents.  Suppose obj1 and obj2 refer to objects of the same type. obj1 == obj2 tests whether both refer to the same object.  Example: obj1.equals(obj2) tests the objects’ contents.  Example: 11 if (obj1 == obj2)... if (obj1.equals(obj2))...

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak Override equals()  Example: Two employees are “equal” if they have the same employee id. 12 public class Employee { private int id;... public boolean equals(Object otherObject) { Employee otherEmployee = (Employee) otherObject; return this.id == otherEmployee.id; } }

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak Override equals(), cont’d  What is printed? 13 package equals; public class EmployeeTester { public static void main(String args[]) { Employee bob1 = new Employee(123, "Smith", "Robert", ); Employee bob2 = new Employee(123, "Smith", "Bob", ); boolean test1 = bob1 == bob2; boolean test2 = bob1.equals(bob2); System.out.println("bob1 == bob2 : " + test1); System.out.println("bob1.equals(bob2) : " + test2); } bob1 == bob2 : false bob1.equals(bob2) : true

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak Override equals(), cont’d  Why did we need the type cast? 14 public boolean equals(Object otherObject) { Employee otherEmployee = (Employee) otherObject; return this.id == otherEmployee.id; }

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak equals() and Inheritance  When you override the equals() method in a subclass, be sure to call the superclass’s equals() method. Example: Suppose, for some bizarre reason, two managers are the same if they have the same employee id and the same bonus. 15 public class Manager extends Employee {... public boolean equals(Object otherObject) { if (!super.equals(otherObject)) return false; Manager otherManager = (Manager) otherObject; return this.bonus == otherManager.bonus; }

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak A Dangerous Typecast  Why is this typecast dangerous? 16 public boolean equals(Object otherObject) { Employee otherEmployee = (Employee) otherObject; return id == otherEmployee.id; }

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak A Dangerous Typecast, cont’d  Yes, this will compile!  What happens when you run it? 17 public class EmployeeTester { public static void main(String args[]) { Employee bob1 = new Employee(123, "Smith", "Robert", ); String bob2 = new String("Robert Smith"); boolean test = bob1.equals(bob2); System.out.println("bob1.equals(bob2) : " + test); }

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak Test with Operator instanceof  One solution: 18 public class Employee {... public boolean equals(Object otherObject) { if (!(otherObject instanceof Employee)) return false; Employee otherEmployee = (Employee) otherObject; return id == otherEmployee.id; }

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak Test with Method getClass()  Why is this even better than using the instanceof operator? 19 public class Employee {... public boolean equals(Object otherObject) { if (otherObject == null) return false; if (this.getClass() != otherObject.getClass()) return false; Employee otherEmployee = (Employee) otherObject; return id == otherEmployee.id; }

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak Break 20

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak Quizzes  Take “Quiz 2 June 9” and “Quiz 5 June 9”  Both are due before class next Tuesday, June 9 21

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak Interfaces  A Java interface is: A set of promises. A contract.  When a class implements an interface, it promises to have all the methods defined by the interface. That’s why an interface is a contract. 22

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak Reasons for Interfaces  Suppose we want to compute the average salaries of some employees. We would write an average() method to compute that average.  Suppose we also want to compute the average weight of some animals. We would write an average() method to compute that average.  Can we use the same average() method to compute both averages? 23

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak Reasons for Interfaces, cont’d  Can we use the same method to compute both averages?  Problem: Class Employee has method getSalary() Class Animal has method getWeight()  We can agree to have both methods named getMeasure().  Problem: Employee and Animal are different types. 24

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak Define a Java Interface  A Java interface definition is similar to a Java class definition:  Some differences from a class definition: All the methods in an interface are abstract. Each method has a name, return type, and parameters, but no implementation. Each interface method is automatically public. 25 public interface Measurable { double getMeasure(); }

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak Implement a Java Interface 26 public class Employee implements Measurable { private double salary; public double getMeasure() { return salary; }... } public class Animal implements Measurable { private double weight; public double getMeasure() { return weight; }... } The getMeasure() methods have the same signature as defined by the interface, but are implemented differently.

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak An Interface is a Type  Employee and Animal are different types. How can a single average() method work with both types?  A Java interface is a type! 27 public class Data { public static double average(Measurable objects[]) { double sum = 0; for (Measurable obj : objects) { sum += obj.getMeasure(); } return objects.length > 0 ? sum/objects.length : 0; }

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak An Interface is a Type, cont’d 28 public class MeasurableTester { public static void main(String args[]) { Measurable employees[] = new Measurable[2]; employees[0] = new Employee(123, "Smith", "Robert", ); employees[1] = new Employee(456, "Jones", "Susan", ); double avgSalary = Data.average(employees); System.out.println("The average salary is " + avgSalary); Measurable animals[] = new Measurable[3]; animals[0] = new Animal("gerbil", 1); animals[1] = new Animal("cat", 10); animals[2] = new Animal("human", 100); double avgWeight = Data.average(animals); System.out.println("The average weight is " + avgWeight); } } Demo

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak Interface Variables  Consider the following two assignment statements: Variable m1 has type Measurable (an interface) and it can refer to a value of type Employee (a class) because Employee implements Measurable. Variable m2 has type Measurable (an interface) and it can refer to a value of type Animal (a class) because Animal implements Measurable. 29 Measurable m1 = new Employee(123, "Smith", "Robert", ); Measurable m2 = new Animal("cat", 10);

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak Interface Variables, cont’d  Valid expressions:  Invalid expressions: 30 Measurable m1 = new Employee(123, "Smith", "Robert", ); Measurable m2 = new Animal("cat", 10); m1.getMeasure(); m2.getMeasure(); m1.getId(); m2.getName(); Why are these expressions valid? Why are these expressions invalid?

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak The Comparable Interface  Any class that implements the Measurable interface promises to have a getMeasure().  How can we make a class promise to allow its instances to be compare to each other? 31 public interface Comparable { int compareTo(Object otherObject); }

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak The Comparable Interface, cont’d  By convention, method compareTo() returns -1 if this object is less than the other object 0 if this object equals the other object 1 if this object is greater than the other object  Regardless of the implementation! 32 public interface Comparable { int compareTo(Object otherObject); }

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak The Comparable Interface, cont’d  Compare Employee salaries: 33 public class Employee implements Comparable { private double salary;... public int compareTo(Object otherObject) { Employee otherEmployee = (Employee) otherObject; if (this.salary < otherEmployee.salary) return -1; if (this.salary > otherEmployee.salary) return 1; return 0; }

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak Implement Multiple Interfaces  A class can implement multiple interfaces. Example: Class Employee promises to implement all the methods in both interfaces Comparable and Measurable.  This is a major difference between classes and interfaces. A class can have only one superclass. A class can implement multiple interfaces. 34 public class Employee implements Comparable, Measurable

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak Practice Homework  Write a Java program that prints Hello, world!  Go to this URL to submit your program: 97x6dcrpyvsnn7z4kt6orx x6dcrpyvsnn7z4kt6orx884 Best with the Firefox browser.  Download the signed zip file.  Submit the signed zip file into Canvas: Assignments/Homework 0 35

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak Homework #1  Two interfaces: 36 public interface Comparable { int compareTo(Object otherObject); } public interface Growable { void increaseBy(double amount); }

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak Homework #1, cont’d  Two implementing classes: 37 public class Animal implements Comparable { private String name; /*** Complete this class. ***/ } public class Employee implements Comparable, Growable { private String name; private double salary; /*** Complete this class. ***/ }

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak Homework #1, cont’d  Animal objects are compared by their names alphabetically.  Employee objects are compared by salaries.  Salaries can be increased. 38

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak Homework #1, cont’d  A utility class that contains a method to find the largest object in an array of objects. 39 public class Utility { public static Comparable max(Comparable objs[]) { /*** Complete this class. ***/ }

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak Homework #1, cont’d  A class for testing. 40 public class Maxima { public static void main(String args[]) { Animal cat = new Animal("cat"); Animal dog = new Animal("dog"); Animal pig = new Animal("pig"); Animal cow = new Animal("cow"); Employee bob = new Employee("bob", ); Employee sue = new Employee("sue", ); Employee ann = new Employee("ann", 50000); Employee tom = new Employee("tom", 75000); Animal zoo[] = new Animal[] {cat, dog, pig, cow}; Employee dept[] = new Employee[] {bob, sue, ann, tom};

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak Homework #1, cont’d  A class for testing, cont’d. 41 Animal maxAnimal = (Animal) Utility.max(zoo); System.out.println("The maximum animal is " + maxAnimal.getName()); Employee maxEmployee = (Employee) Utility.max(dept); System.out.println("The maximum employee is " + maxEmployee.getName()); ann.increaseBy(20000); bob.increaseBy(60000); maxEmployee = (Employee) Utility.max(dept); System.out.println("The maximum employee is " + maxEmployee.getName()); } }

Computer Science Dept. Summer 2015: June 4 CS 46B: Introduction to Data Structures © R. Mak Homework #1, cont’d  Go to URL 3s77uby9jo4sowst4ay96aljm 3s77uby9jo4sowst4ay96aljm  Complete classes Animal, Employee, and Utility and then submit.  When you have a solution that passes, download the signed zip file.  Submit the zip file in Canvas under Assignments/Homework 1 Final 42 Due Monday, June 8 at 11:50 PM