Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts Georgia Institute of Technology
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 Some object-oriented languages don’t have classes. They use object prototypes instead. Georgia Institute of Technology
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 Create the class definition in the exercises/Student directory. 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
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 Class fields and methods have the keyword “static” on them. Object fields and methods do not have the keyword “static”. Georgia Institute of Technology
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
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 You can start with your previous Student.java file or use exercises/Student-Id/Student.java. Georgia Institute of Technology
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() The Class objects holds information from the class definition Sally:Student firstName lastName pictureFile grades Student: Class numStudents addGrade(grade) getGradePointAverage() … For every class loaded into a Java virtual machine there is a class java.lang.Class that defines it. Georgia Institute of Technology
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? You can start with your previous Student.java file or use exercises/Student-Class-Id/Student.java. 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
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 Inexperienced programmers and procedural programmers often overuse class methods. Georgia Institute of Technology
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 Parent Student Child This type of diagramming is called UML which is the Unified Modeling Language and is a standard way to show object-oriented designs. Georgia Institute of Technology
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
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
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 Some other ideas are (teacher, math teacher), (school, elementary school, middle school, high school) Georgia Institute of Technology
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
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 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 You can’t directly access private inherited field because these can only be directly accessed in the same class. 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! Even though you can declare your class final so that other classes can’t inherit from it you can’t lock a package. The only use for protected is to use it for methods that you might want your children to override. 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
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) The Picture p = new SimplePicture(fileName) won’t compile since you can’t substitute a parent object for a child object. If I ask you for a dictionary just a book wouldn’t do. Georgia Institute of Technology
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
Georgia Institute of Technology Specialization Person firstName lastName pictureFile 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 Student id nickname grades numGrades numStudents getGradePointAverage() Notice that you can’t take away methods or fields. Georgia Institute of Technology
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 We know it will find a corresponding method since it wouldn’t have compiled otherwise. Georgia Institute of Technology
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() The String You should always override hashCode when you override equals for consistent behavior with Collection classes. Georgia Institute of Technology
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 A real key would have a location printed on it which locates the box that the key fits. Georgia Institute of Technology
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 You can start with Student.java from a previous exercise or use the one in exercises/Student-Override. 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
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; Final variables mean that variable can not change value. Final methods can not be overridden. Final classes can’t be subclassed. The Java convention is to uppercase all the letters in a constant. Multiple words are separated by underscores: THIS_IS_A_CONSTANT. Georgia Institute of Technology
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
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 Food price calories Hamburger Coke The compiler will give an error if you try to create an object of an abstract class. You can use abstract classes as a way of generalizing attributes and methods. Can your order “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
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 Interfaces are declared in files with the interface name and the .java extension. Notice that you don’t have to declare the methods to be abstract. This is automatic with interfaces. 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 } } The compiler will give error messages if the ShapeCanvas class doesn’t provide the implementations of the setShape and setShapeColor methods. Georgia Institute of Technology
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
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) The method compareTo returns a negative number if the current object is less than the passed object, 0 if they are equal, and a positive number if the passed object is greater than the current object. Georgia Institute of Technology
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
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
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 ShapeInterface 1 1 1 1 Shape ShapeCanvas ButtonPanel 1 * draw() paint() Oval Rectangle Class ShapePanel can be used in a application or applet. A ShapePanel object has one ShapeCanvas and one ButtonPanel in it. The ShapeCanvas holds 0 to many Shapes. The ShapeCanvas implements the ShapeInterface. Shape is an abstract class with the abstract method draw in it. Oval and Rectangle both inherit from Shape and implement draw. draw() draw() Georgia Institute of Technology
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. Edit ShapeInterface.java and add the declaration of the method clearShapes. public void clearShapes(); Edit ShapeCanvas.java and implement the method clearShapes public void clearShapes() { shapes. clear(); // remove all shapes from the vector repaint(); // repaint to see that shapes are gone } Edit ButtonPanel to add the clear button and have it call clearShapes on the ShapeInterface handler 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 Rectangle draw() 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. Edit Oval.java and save it as Line.java. Modify the draw method of Line.java to draw a line. g.drawLine(p1.x,p1.y,p2.x,p2.y); Edit Shape.java and add a constant for Line. public static final String LINE = ”Line”; Edit ButtonPanel.java and add a line button that when clicked calls the handler’s setShape with a line as the current shape. handler.setShape(Shape.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
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