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 :Student JaKita :Student Thomas :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() Sally:Student firstName lastName pictureFile grades Student: Class • The Class objects holds information from the class definition 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 Person Parent Student Child • The class you inherit from is called – Parent, superclass, base class • The class doing the inheriting is called – Child, subclass, derived class 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 – http://java.sun.com/j2se/1.4.2/docs/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 Food subclassed. price calories Hamburger Coke • Create an abstract class by using the keyword abstract in the class declaration. – public abstract class Food 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 <<interface>> Collection <<interface>> List ArrayList Vector <<interface>> Set LinkedList HashSet <<interface>> SortedSet TreeSet 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 ShapePanel ShapeInterface 1 Shape draw() Oval draw() * 1 1 1 ShapeCanvas paint() Rectangle draw() Georgia Institute of Technology 1 ButtonPanel 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 Georgia Institute of Technology