Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.

Slides:



Advertisements
Similar presentations
1 Chapter 6: Extending classes and Inheritance. 2 Basics of Inheritance One of the basic objectives of Inheritance is code reuse If you want to extend.
Advertisements

AbstractClassesInterfacesPolymorphism1 Abstract Classes, Interfaces, Polymorphism Barb Ericson Georgia Tech April 2010.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
Inheritance Inheritance Reserved word protected Reserved word super
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,
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Polymorphism. Lecture Objectives To understand the concept of polymorphism To understand the concept of static or early binding To understand the concept.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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.
Programming Languages and Paradigms Object-Oriented Programming.
18 - Abstract Classes, Polymorphism, and Inheritance 1 Abstract Classes, Polymorphism, and Inheritance Barb Ericson Georgia Institute of Technology Dec.
CPSC1301 Computer Science 1 Chapter 11 Creating Classes part 1.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
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.
CreatingClasses-part11 Creating Classes part 1 Barb Ericson Georgia Institute of Technology Dec 2009.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Georgia Institute of Technology Creating Classes part 1 Barb Ericson Georgia Institute of Technology Oct 2005.
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.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
Data structures Abstract data types Java classes for Data structures and ADTs.
15440 Distributed Systems Recitation 1 Objected-Oriented Java Programming.
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.
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.
Types in programming languages1 What are types, and why do we need them?
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
CreatingSubclasses1 Barb Ericson Georgia Institute of Technology Dec 2009.
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.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Object Oriented Programming
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Coming up: Inheritance
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
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.
Georgia Institute of Technology More on Creating Classes part 3 Barb Ericson Georgia Institute of Technology Nov 2005.
1 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Georgia Institute of Technology Comic Strip Analysis and Design Inheritance, Abstract Classes, and Polymorphism part 2 Barb Ericson Georgia Institute of.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
Georgia Institute of Technology Comic Strip Analysis and Design Inheritance, Abstract Classes, and Polymorphism part1 Barb Ericson Georgia Institute of.
Georgia Institute of Technology More on Creating Classes Barb Ericson Georgia Institute of Technology June 2006.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Lecture 10 – Polymorphism Nancy Harris with additional slides Professor Adams from Lewis & Bernstein.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Object-Oriented Design
Sixth Lecture ArrayList Abstract Class and Interface
Object-oriented Programming in Java
03/10/14 Inheritance-2.
Java Programming Language
Workshop for CS-AP Teachers
Barb Ericson Georgia Institute of Technology Oct 2005
Workshop for Programming And Systems Management Teachers
More on Creating Classes
Creating and Modifying Text part 3
CS 240 – Advanced Programming Concepts
Presentation transcript:

Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts

Georgia Institute of Technology Learning Goals Understand at a conceptual and practical level –Objects Object variables and methods –Classes Class variables and methods –Inheritance –Abstract Classes –Interfaces –Polymorphism

Georgia Institute of Technology Object-Oriented Principles Objects with data (fields) and operations (methods) –Usually classes too Inheritance –Hierarchy of types –Generalization / Specialization Polymorphism –Executing the right method based on the type of the object at run-time

Georgia Institute of Technology Advantages to Objects Data and related operations are combined –No passing data around –Data is protected Objects are responsible –If code needs to be fixed you can figure out what class needs to be changed –Methods can change as long as they still do the job Easier to maintain and extend –Objects don’t change as often as procedures –The program is a simulation of the domain Classes can be reused

Georgia Institute of Technology Class Definition Exercise Write the definition for a class Student. –We need to know about the student’s name (first and last), store the name of a file with his or her picture in it, and keep the grades for this student. We want to be able to add grades and compute the grade point average. Remember to define methods to get and set all fields Write the main method to create a Student

Georgia Institute of Technology Steps in a Class Definition Underline the nouns and verbs –Nouns may be attributes Sometimes other classes –Verbs may be methods Do a simple UML class –Class name, attributes (fields), methods –Specify the types of the attributes –Specify the return type and parameter types Code the class

Georgia Institute of Technology Class Definition A class definition in Java defines –Object Fields (Variables) Fields that all objects of the class will have –Class Fields (Variables) Fields that will only be on the class definition class –Constructors Used to initialize object fields –Object Methods Methods that have the current object passed implicitly (this) –Class Methods Methods that operate on class variables

Georgia Institute of Technology Adding a Student Id What if we want to add an id as an object field? –Each object should have a unique id –One way to assign a unique id is to have a counter that counts how many students we have Increment the current count each time a new student is created Use the current count as the id

Georgia Institute of Technology Adding Id Exercise Modify the Student class to add a unique id for each student –Add the field id –Add the field numStudents that starts out as 0 Each time a new student is created –Increment numStudents –Set the id to the numStudents –Modify the toString method to add the id –Create several students in the main method

Georgia Institute of Technology What went wrong? id and numStudents are object fields –A separate copy is in each object –So all objects have a count of 0 But we want there to only be only one copy of the number of students –That all Student objects have access to Sally :StudentJaKita :StudentThomas :Student numStudents

Georgia Institute of Technology Class Fields (Variables) Each object has a link to an object that describes the class –An object of the class “java.lang.Class” So if we create a class field –All objects will have access to the one field Create class fields –Using the keyword static Sally:Student Id firstName lastName pictureFile grades Student: Class numStudents addGrade(grade) getGradePointAverage() …

Georgia Institute of Technology An Object “knows” what Class it is You can check that an object is of a class instanceof ClassName You can get the Class object from an object getClass() The Class objects holds information from the class definition Sally:Student firstName lastName pictureFile grades Student: Class numStudents addGrade(grade) getGradePointAverage() …

Georgia Institute of Technology Class Exercise Loop up the class java.lang.Class –How do you get the parent class of a class? –How do you get the methods of a class? –How do you get the fields of a class? –How do you tell if it is an interface? Try the following in DrJava –Class stringClass = “Test”.getClass(); –System.out.println(stringClass); –System.out.println(stringClass.newInstance());

Georgia Institute of Technology Class Variable Exercise Make numStudents a class variable by adding the keyword static Now run the main method and check that the ids are unique and incrementing Create another student in the main and run it again –What id does the first student start with?

Georgia Institute of Technology Object Methods versus Class Methods Object methods are implicitly passed the current object –And work on the data in that object Class methods only have access to class fields –They are not passed an object of the class They can not work on object data –They are useful when you don’t have a current object –They are useful for working with class fields

Georgia Institute of Technology Class Method Exercise When should you use a class method and when an object method? –To read a file and create student objects from the information in the file –To get the grade point average for a student –To get the number of student objects created –To print the information in a student object

Georgia Institute of Technology Inheritance Did you get features or abilities from your parents? –People inherit physical characteristics –Some people inherit abilities: music Inheritance in OO means receiving data and methods from your parent –In Java you can only have one parent

Georgia Institute of Technology Inheritance in our Models One class can inherit from another –Gets all the fields and methods The class you inherit from is called –Parent, superclass, base class The class doing the inheriting is called –Child, subclass, derived class Person Student Parent Child

Georgia Institute of Technology Inheritance Exercise Open the Picture class (Picture.java) –See if you can find the show method Notice that the Picture class extends (inherits) from SimplePicture –See if you can find the show method in SimplePicture Since Picture inherits from SimplePicture you can ask a Picture object to show itself

Georgia Institute of Technology How Inheritance Works When an object gets a message it checks to see if it has a corresponding method –If it does it executes that method –If it doesn’t it checks the parent class And keeps looking at parents until the method is found or it reaches Object The Java compiler makes sure that a method is available –based on the declared type of the object

Georgia Institute of Technology Teaching Inheritance Point out inheritance in common objects –What is a book? –What is a dictionary? Talk about the things that are the same Talk about the things that are different

Georgia Institute of Technology The Object Class If you don’t specify a parent for a class using “extends” it will inherit from Object –public class Name { All objects in Java inherit from Object –Directly or indirectly Object is in the package java.lang All objects inherit –toString() and equals() but you will usually override these

Georgia Institute of Technology Inheritance Exercise Look up Object in the api – –In package java.lang –What other public methods are in Object? Look up String in the api –In package java.lang –What class does it inherit from? Look up JButton in the api –In package javax.swing –What are all the classes it inherits from?

Georgia Institute of Technology Private Visibility and Inheritance When a class inherits from another class it gets all the fields and methods But, it can’t directly access fields or methods that are private –Use public methods to ask for changes to private fields –Call public methods that call private methods This is to allow an object to protect its data and keep private methods private

Georgia Institute of Technology Protected and Inheritance Some books use protected visibility with inheritance for fields –To give children objects direct access to fields This is a bad idea –Protected gives access to subclasses –Protected also gives access to all classes in the same package You can’t guarantee the data isn’t messed up by objects of other classes if you use protected fields!

Georgia Institute of Technology When to Use Inheritance Use inheritance when one class is really a sub-type of another You must be able to substitute an object of the child class for an object of the parent class and still have it make sense Don’t use it just to have access to some fields and methods of the parent class –Use an association (has a) link instead

Georgia Institute of Technology Correct Use of Inheritance Students and Teachers are people –You could use a student or teacher when you need a person A course period is not a course –You wouldn’t include a course period in a list of available courses –Instead a course period would have a course associated with it Have a field that is a Course object

Georgia Institute of Technology Substitution Is a dictionary a book? –If you need a book will a dictionary work? You can use a child object when a variable refers to a parent object –SimplePicture p = new Picture(fileName); You can’t substitute a parent for a child –Picture p = new SimplePicture(fileName)

Georgia Institute of Technology Generalization Generalization means that classes have things in common If they are several classes that all have the same or similar fields and methods –pull out the common items and put them in a parent class

Georgia Institute of Technology Generalization - Exercise Pull out common fields and methods in Student and Teacher and put them in a new class Person –Modify constructors as needed Have student and teacher inherit from Person Run the main methods in Student and Teacher after the changes –To make sure they still work

Georgia Institute of Technology Specialization A class differs from the parent class in some way –It add fields –It adds methods –It does something different when given the same message as the parent Person firstName lastName pictureFile Student id nickname grades numGrades numStudents getGradePointAverage()

Georgia Institute of Technology Overriding Methods One way a child class can specialize is to handle the same message in a different way than the parent If you inherit parent methods how can you do this? The child can redefine a method with the same name and parameters as the parent method –The new method is called instead of the parent method –This is called overriding

Georgia Institute of Technology How Does Overriding Work? When a message is sent to an object The object checks with its class to see if the corresponding method exists in the class If it doesn’t exist in the class then it checks in the parent class It keeps looking up the inheritance tree till it finds a corresponding method

Georgia Institute of Technology Using Super What if the method in the child class wants to call the method in the parent class? –I want to do the same operation as my parent but also add something to it –But my method overrides the parent method Use the keyword super to invoke an overridden parent method –super.method() –It starts looking for a corresponding method in the parent class

Georgia Institute of Technology Overriding equals and hashCode All classes inherit from Object the method –public boolean equals(Object o) –the default result is true if they are the same object else false You will often want to override this method –And check if some field or fields are equal If you override equals you must also override hashCode –public int hashCode()

Georgia Institute of Technology What is a hash code? An integer used to index into –hashing based collection classes such as Hashtable, HashMap, HashSet What should you return as a hash code? –Best if each object has a unique hash code –Okay if most objects have a unique hash code But some have duplicates –Bad if most objects result in duplicate hash codes

Georgia Institute of Technology What is a Hashing Collection? Map of key to value –You put a value (object) into a collection for a key (object) –You can get back the value for that key Similar to a safety deposit box The hashCode() method is used on the key to find the memory location holding the value –The address of it

Georgia Institute of Technology Overriding Exercise Edit Student.java to override equals() –public booelan equals(Object object) Return true if the passed object isn’t null and is of the class Student –And the id of the current object and passed student object are equal Override hashCode() –You can return the id since each object will have a unique id Test equals in the main method

Georgia Institute of Technology Advantages to Inheritance Handles commonality –Common attributes and operations are factored out and put as high as possible in a hierarchy –Not copied to several locations Handles differences –Children can inherit the parts that are common from the parent –They can add attributes and operations to handle how they differ from the parent –They can override operations (methods) to do something different from the parent

Georgia Institute of Technology Constants The final keyword means that the item will not change. By using the final keyword along with public and static you can create class fields that are constant. –public static final int MALE = 0; These can be accessed by using the Class name.attribute name. –this.gender = Person.MALE;

Georgia Institute of Technology Constant Exercise Add constants for unknown, male, and female gender to Person.java –public static final int UNKNOWN = 0; –public static final int FEMALE = 1; –public static final int MALE = 2; Add a gender field to Person.java –private int gender = UNKNOWN; // default Add get and set gender methods Add gender to the result of toString()

Georgia Institute of Technology Abstract Classes Abstract classes are classes that can’t be instantiated. Abstract classes can only be subclassed. Create an abstract class by using the keyword abstract in the class declaration. –public abstract class Food HamburgerCoke Food price calories

Georgia Institute of Technology Why use an Abstract Class? Represents an abstract idea (like Shape) Holds methods common to several related classes Holds attributes common to several related classes Enforce naming convention by abstract methods that must be overridden by children Allows for general algorithms based on abstract methods with customization by children

Georgia Institute of Technology Interfaces Interfaces are a description of behavior. –They are a special kind of abstract class that has only abstract methods and constants. public interface ShapeInterface { public void setShape(int shape); public void setShapeColor(Color shapeColor); } –You don’t have to declare the methods as abstract They automatically are

Georgia Institute of Technology Classes Implement Interfaces Classes that implement interfaces must provide the implementations for the methods specified in the interface. public class ShapeCanvas implements ShapeInterface { public void setShape(int shape) { code to handle set shape } public void setShapeColor(Color shapeColor) { code to handle set shape color } }

Georgia Institute of Technology Why use an Interface? Separates what from who –I don’t care who you are I just need a way to talk to you –Choose from several implementers A class can implement many interfaces but inherit from only one class –like multiple inheritance but easier to use –thinner than inheritance

Georgia Institute of Technology Interfaces Versus Inheritance When a class inherits from a parent class it inherits all the attributes and methods. –With inheritance it inherits the structure and behavior of the parent class. –With an interface it inherits only the method names and parameter lists. A class can inherit from only one parent class –public class Person extends Object A class can implement more than one interface. –public class ShapeCanvas implements Interface1,Interface2,…

Georgia Institute of Technology Compare Interface How would you compare any two objects? –And decide if one is less than, equal too, or greater than the other It would depend on the Class of the objects being compared –For String objects compare the letters in the string Implement the Comparable interface –public int compareTo(Object object)

Georgia Institute of Technology Comparable Exercise How would you compare two Person objects? –Implement the Comparable interface public int compareTo(Object object) –Compare the last names first If they are equal compare the first names –The String class implements Comparable so you can use the results of comparing the last name and first name

Georgia Institute of Technology Collections - java.util Used to hold objects –Use wrapper classes to hold primitive values int numItems = 3; Integer numItemsInt = new Integer(numItems); Three basic types –List - ordered list of objects Can have duplicate objects –Set - group of objects without an order No duplicate objects allowed –Map - map of keys to objects

Georgia Institute of Technology List and Set Interfaces and Classes > Collection > List > Set > SortedSet ArrayList Vector LinkedList TreeSet HashSet

Georgia Institute of Technology Collection Methods Add an object to a collection boolean add(Object object); // optional Remove an object from a collection boolean remove(Object object); //optional See if the collection has the object in it boolean contains(Object object); Add all objects in another collection boolean addAll(Collection collection); // optional Get the intersection of two collections boolean retainAll(Collection collection); // optional Empty a collection Void clear();

Georgia Institute of Technology Use Interface Name as Type Declare the type of the collection variable to be one of the main interface types –List –Set SortedSet –Map SortedMap This allows you to change the implementation without changing much code Map addressMap = new HashMap(); Map addressMap = new Hashtable();

Georgia Institute of Technology Polymorphism Literally: many forms In Object-Oriented development it means that what happens when a message is sent to an object depends on the type (class) of the object at runtime

Georgia Institute of Technology How Does Polymorphism Work? If a class is declared to be final –then the compiler can figure out the location of a method that matches the message If a class can be subclassed –then a variable declared to be of the parent type can point to an object of the parent class or any subclass at run-time –the compiler can’t determine the method to invoke –the method to invoke is figured out at run-time

Georgia Institute of Technology Shape Panel Exercise Execute the main method of ShapePanel Click the Rectangle button and then click and drag to position the rectangle Click the Oval button and click and drag to position the oval

Georgia Institute of Technology Class Diagram for ShapePanel Shape draw() Oval draw() Rectangle draw() ShapeCanvas paint() ShapePanel ButtonPanel 1 1 * ShapeInterface 1 1 1

Georgia Institute of Technology Interface Exercise –Add a method to the ShapeInterface public void clearShapes(); –Modify the ShapeCanvas class to implement the method and clear the vector of shapes and then call repaint(); –Modify the ButtonPanel class to add the clear button and have it call clearShapes() when pressed.

Georgia Institute of Technology Polymorphism - Many Forms Polymorphism is overloading that is resolved at execution time, and is also called dynamic or run-time binding. Say you have an array of Shapes that actually holds objects that are subclasses of shape. –When you ask a shape to draw itself what gets drawn depends on the run-time type. Shape draw() Oval draw() Rectangle draw()

Georgia Institute of Technology Add Abstract Class Subclass Exercise –Create a new class Line which is a subclass of Shape. –Add a constant for Line to the Shape class. –Add a Line Button to the Button Panel and when the line button is clicked on notify the handler to set the shape to line.

Georgia Institute of Technology Advantages to Polymorphism Used to create general algorithms that work on objects of different types –Collections that hold Objects List, Set, Stack, Queue, Map Makes it easy to add new types –Just create the new class and implement the required operations –Don’t change existing code

Georgia Institute of Technology Summary Class fields are on an object of the class Class –Not on objects of the class Class methods can only work on class fields –Not object fields Objects inherit fields and methods from a parent class –But need to use public methods to access private inherited fields Polymorphism allows you to write general methods based on a common parent or interface