Lecture 8: Object-Oriented Design. 8-2 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Objectives “Good object-oriented programming is really.

Slides:



Advertisements
Similar presentations
Chapter 13 - Inheritance. Goals To learn about inheritance To learn about inheritance To understand how to inherit and override superclass methods To.
Advertisements

Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
OBJECT-ORIENTED PROGRAMMING. What is an “object”? Abstract entity that contains data and actions Attributes (characteristics) and methods (functions)
Inheritance, part 2: Subclassing COMP 401, Fall 2014 Lecture 8 9/11/2014.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
CS 106 Introduction to Computer Science I 11 / 20 / 2006 Instructor: Michael Eckmann.
CS2200 Software Development Lecture: Object class A. O’Riordan, 2008.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
1 Inheritance Overview l Inheritance ensures Reusability l Example of Inheritance l What is actually Inherited? l Overloading Vs. Overriding l Object:
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 04 / 21 / 2008 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 04 / 28 / 2010 Instructor: Michael Eckmann.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
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.
Inheritance One of the biggest advantages of object-oriented design is that of inheritance. A class may be derived from another class, the base class.
Advanced Inheritance Concepts. In this chapter, we will cover: Creating and using abstract classes Using dynamic method binding Creating arrays of subclass.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
CISC6795: Spring Object-Oriented Programming: Polymorphism.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Computer Science and Engineering College of Engineering The Ohio State University Lot More Inheritance and Intro to Design Patterns Lecture 12.
Object-oriented Programming in Java. What is OOP?  The goal is (subtype) polymorphism  Achieved by Classes (user-defined types) Classes (user-defined.
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Object-Oriented Design CSC 212. Announcements This course is speeding up and we are starting new material. Please see me if you feel this is going too.
CS 106 Introduction to Computer Science I 04 / 23 / 2010 Instructor: Michael Eckmann.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Topic 4 Inheritance.
Programming in Java CSCI-2220 Object Oriented Programming.
Teach.NET Workshop Series Track 4: AP Computer Science with.NET and J#
Inheritance (Part 5) Odds and ends 1. Static Methods and Inheritance  there is a significant difference between calling a static method and calling a.
Inheritance and Access Control CS 162 (Summer 2009)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Inheritance (Part 2) KomondorBloodHound PureBreedMix Dog Object.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Java Programming, Second Edition Chapter Twelve Advanced Inheritance Concepts.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
(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 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Inheritance and Polymorphism
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
1 Inheritance One of the goals of object oriented programming is code reuse. Inheritance is one mechanism for accomplishing code reuse. It allows us to.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Inheritance ITI1121 Nour El Kadri.
Lecture 12 Inheritance.
Object-oriented Programming in Java
Inheritance and Polymorphism
Extending Classes.
Java Programming Language
Object-Oriented Programming
Advanced Inheritance Concepts
CIS 110: Introduction to computer programming
Presentation transcript:

Lecture 8: Object-Oriented Design

8-2 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Objectives “Good object-oriented programming is really about good object- oriented design. And good OOD is all about making things easier for ourselves, as well as for our class users…” Class design Inheritance Interfaces

8-3 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Part 1 Class design…

8-4 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Class design rules #1 – #4 These rules you probably already know: 1." Classes should provide constructors " – to ensure initialization of fields 2." Classes should provide methods to manipulate class fields " – e.g. bank Customer's getFormattedBalance( ) or makeDeposit(amt) 3." Classes should practice data-hiding, and control access otherwise" – use of private keyword, get & set methods for field access 4." Classes should override toString( ) " – to return appropriate string-based representation

8-5 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Class design rule #5 " Classes should override Equals( ) " –enables object equality to be determined based on fields Example: –students are equal if their IDs are the same public class Student { private int id;. public boolean equals(Object obj) { // make sure we are comparing apples to apples… if (obj == null || !(obj.getClass().equals(this.getClass()))) return false; // we know obj is a student but J# doesn't, so type-cast to Student so we can compare IDs… Student other = (Student) obj; return this.id == other.id; } public class Student { private int id;. public boolean equals(Object obj) { // make sure we are comparing apples to apples… if (obj == null || !(obj.getClass().equals(this.getClass()))) return false; // we know obj is a student but J# doesn't, so type-cast to Student so we can compare IDs… Student other = (Student) obj; return this.id == other.id; } if (s1.equals(s2))...

8-6 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Class design rule #6 " Classes that override Equals( ) should also override hashCode( ) " –Java rule: equal objects must have equal hash codes –Solution? Base hashCode( ) on same field(s) as equals( ) Example: –student's hash code is their ID! public class Student { private int id;. public int hashCode() { return this.id; // equal students will have same hash code! } public class Student { private int id;. public int hashCode() { return this.id; // equal students will have same hash code! }

8-7 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Part 2 Inheritance…

8-8 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Inheritance One class may extend another class, inheriting all fields & methods: Why do this? –Code reuse! Class B doesn't have to reinvent class A… –Design reuse! Class B "is-a" class A, and treated as such… public class B extends A {. } public class B extends A {. }

8-9 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Example Student firstName : String lastName : String id : int gpa : double Student(fn, ln, id, gpa) get_firstName( ) : String... Freshman Sophomore Junior Senior super / base / parent sub / derived / child Student class hierarchy: extends

8-10 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Superclass design Superclass can define members as private, protected, or public Superclass can define common functionality for its subclasses Superclass can define abstract methods for subclasses to implement public abstract class Student { protected String firstName, lastName; protected int id; protected double gpa;. public String getFormattedGPA() { java.text.DecimalFormat formatter; formatter = new java.text.DecimalFormat("0.00"); return formatter.format(this.gpa); } public abstract boolean meetsMinGPA(); } public abstract class Student { protected String firstName, lastName; protected int id; protected double gpa;. public String getFormattedGPA() { java.text.DecimalFormat formatter; formatter = new java.text.DecimalFormat("0.00"); return formatter.format(this.gpa); } public abstract boolean meetsMinGPA(); }

8-11 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Subclass design Subclasses are responsible for: –calling their superclass's constructor –implementing any abstract methods public class Freshman extends Student { public Freshman(String fn, String ln, int id, double gpa) { super(fn, ln, id, gpa); } public boolean meetsMinGPA() { // freshman must maintain a GPA of 1.5 or greater... return this.gpa >= 1.5; } public class Freshman extends Student { public Freshman(String fn, String ln, int id, double gpa) { super(fn, ln, id, gpa); } public boolean meetsMinGPA() { // freshman must maintain a GPA of 1.5 or greater... return this.gpa >= 1.5; }

8-12 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Polymorphism Poly-whatism ? Polymorphism is about writing code in a general way –the more general the code, the more reusable in new situations More formally: –Definition: polymorphism is when different types support the same operation, allowing the types to be treated similarly. –this allows the same code to work on a wider range of types Example? –Student objects and meetsMinGPA( ) –next page…

8-13 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Example: meetsMinGPA( ) meetsMinGPA() is an example of a polymorphic method –defined in super class so all students support it –implemented in subclasses so each implementation may differ Advantage? –the following code correctly checks *all* types of students to ensure they are meeting minimum GPA requirements! java.util.ArrayList students = new java.util.ArrayList(); students.add( new Freshman(…) ); // a Freshman is-a Student… students.add( new Junior(…) ); // a Junior is-a Student…. for (int i = 0; i < students.size(); i++) { Student s = (Student) students.get(i); if (!s.meetsMinGPA()) System.out.println("Min GPA violation: " + s); } //for java.util.ArrayList students = new java.util.ArrayList(); students.add( new Freshman(…) ); // a Freshman is-a Student… students.add( new Junior(…) ); // a Junior is-a Student…. for (int i = 0; i < students.size(); i++) { Student s = (Student) students.get(i); if (!s.meetsMinGPA()) System.out.println("Min GPA violation: " + s); } //for

8-14 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET. for (int i = 0; i < students.size(); i++) { Student s = (Student) students.get(i); if (!s.meetsMinGPA()). for (int i = 0; i < students.size(); i++) { Student s = (Student) students.get(i); if (!s.meetsMinGPA()) Dynamic binding Dynamic binding is the technology that enables polymorphism When you make a method call: 1.Java dynamically determines the type of the object, then 2.Java binds to ("calls") the correct method based on object's type (1) What type of object: Freshman, Sophomore, Junior, or Senior? (2) Based on answer to (1), dynamically bind to (i.e. "call") the correct implementation of the meetsMinGPA( ) method in Freshman, Sophomore, Junior, or Senior.

8-15 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Overriding equals, part 2 Problem: –suppose we override equals( ) as discussed earlier, which requires that objects be exactly the same type to be equal –in this case, how do we search for students? java.util.ArrayList students = new java.util.ArrayList();. int loc, id; Student s; id =...; // id of student we are looking for… s = new ????????? ("", "", id, 0.0); // create temp object for search loc = students.indexOf(s); // linear search for actual student… java.util.ArrayList students = new java.util.ArrayList();. int loc, id; Student s; id =...; // id of student we are looking for… s = new ????????? ("", "", id, 0.0); // create temp object for search loc = students.indexOf(s); // linear search for actual student… What class do we use?

8-16 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Overriding equals again… Instead of requiring exactly the same types, check to make sure both objects inherit from Student… –we know "this" object does, just a matter of checking "obj"… public abstract class Student { private int id;. public boolean equals(Object obj) { // make sure we are comparing apples to apples… if (obj == null || !(obj.getClass().equals(this.getClass()))) return false; // we know obj is a student but J# doesn't, so type-cast to Student so we can compare IDs… Student other = (Student) obj; return this.id == other.id; } public abstract class Student { private int id;. public boolean equals(Object obj) { // make sure we are comparing apples to apples… if (obj == null || !(obj.getClass().equals(this.getClass()))) return false; // we know obj is a student but J# doesn't, so type-cast to Student so we can compare IDs… Student other = (Student) obj; return this.id == other.id; } !(obj instanceof Student))

8-17 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Linear search again… Now you can search by creating any kind of object you want: –except for Student, which won't work since it's abstract java.util.ArrayList students = new java.util.ArrayList();. int loc, id; Student s; id =...; // id of student we are looking for… s = new Senior("", "", id, 0.0); // create temp object for search loc = students.indexOf(s); // linear search for actual student… if (loc >= 0) System.out.println("Found at location " + loc); java.util.ArrayList students = new java.util.ArrayList();. int loc, id; Student s; id =...; // id of student we are looking for… s = new Senior("", "", id, 0.0); // create temp object for search loc = students.indexOf(s); // linear search for actual student… if (loc >= 0) System.out.println("Found at location " + loc);

8-18 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Part 3 Interfaces & design by contract…

8-19 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Motivation We program by relying on "contracts" –i.e. agreements between objects –"Object X agrees to do Y, so I'll call X when I need to do Y" java.io.FileReader file = new java.io.FileReader("…"); java.io.BufferedReader reader = new java.io.BufferedReader(file); s = reader.readLine(); java.io.FileReader file = new java.io.FileReader("…"); java.io.BufferedReader reader = new java.io.BufferedReader(file); s = reader.readLine(); public class BufferedReader {. public String readLine() {. } public class BufferedReader {. public String readLine() {. }

8-20 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Design by contract Design by contract formalizes this process –design first –implement second Advantages? –encourages "think before you code" –ensures integration of classes in a large program –different classes supporting the same contract offer another means of polymorphic programming !

8-21 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Interfaces Interfaces are a formal way of specifying contracts An interface = a set of method signatures –representing the contract between two or more parties –pure design, no data / code public interface SomeInterfaceName { public void Method1(); public int Method2(int x, String y);. } public interface SomeInterfaceName { public void Method1(); public int Method2(int x, String y);. }

8-22 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Conceptual view Here's how to visualize what's going on: "server" (object performing service according to interface contract) "client" (object requesting service) Interface –"client" uses interface to communicate with server –"server" implements interface to fulfill contract

8-23 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Example Sorting and binary search These algorithms are a part of the Java Class Library –but use an interface to communicate with objects… sort( ) object binarySearch( ) object

8-24 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET (1) Comparable interface Defines the comparison of two objects, returning an integer: –< 0 means this object < obj –= 0 means this object = obj –> 0 means this object > obj public interface Comparable { public int compareTo(Object obj); } public interface Comparable { public int compareTo(Object obj); } if (s1.compareTo(s2) < 0)...

8-25 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET (2) Objects implement Comparable To fulfill contract, objects must implement Comparable: public abstract class Student implements Comparable { private int id;. public int compareTo(Object obj) { // make sure we are comparing apples to apples… Student other = (Student) obj; if (this.id < other.id) return -1; else if (this.id == other.id) return 0; else return 1; } public abstract class Student implements Comparable { private int id;. public int compareTo(Object obj) { // make sure we are comparing apples to apples… Student other = (Student) obj; if (this.id < other.id) return -1; else if (this.id == other.id) return 0; else return 1; } student

8-26 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET (3) Call sort() and binarySearch() Now we can take advantage of these built-in algorithms: java.util.ArrayList students = new java.util.ArrayList(); students.add( new Freshman(…) ); students.add( new Junior(…) );. java.util.Collections.sort(students); int loc, id; Student s; id =...; // id of student we are looking for… s = new Senior("", "", id, 0.0); // create temp object for search loc = java.util.Collections.binarySearch(students, s); if (loc >= 0) System.out.println("Found at location " + loc); java.util.ArrayList students = new java.util.ArrayList(); students.add( new Freshman(…) ); students.add( new Junior(…) );. java.util.Collections.sort(students); int loc, id; Student s; id =...; // id of student we are looking for… s = new Senior("", "", id, 0.0); // create temp object for search loc = java.util.Collections.binarySearch(students, s); if (loc >= 0) System.out.println("Found at location " + loc);

8-27 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Summary Good OOP is all about good Object-Oriented Design Java, J# and.NET all employ a great deal of OOD –effective use requires a solid understanding of OOD –e.g. linear search is built-in, but you need to implement equals() –e.g. sorting & binary search are built-in, but you need to implement Comparable and compareTo() Inheritance & interfaces are important OOD tools –look for ways to create / exploit polymorphism