1 / 56

APCS-A: Java

APCS-A: Java. Inheritance November 28, 2005. Checkpoint. USB drives (check-out form) Quiz/Project graded, but waiting for make-ups, still need some old labs from some of you We’re entering a new topic completely, adding a level of complexity to what we have done so far.

kiana
Download Presentation

APCS-A: Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. APCS-A: Java Inheritance November 28, 2005

  2. Checkpoint • USB drives (check-out form) • Quiz/Project graded, but waiting for make-ups, still need some old labs from some of you • We’re entering a new topic completely, adding a level of complexity to what we have done so far. • Any questions about anything before we go on???

  3. Making a Zoo • If we wanted to model a zoo, what kind of objects would we need? • What would those objects do? (i.e. what are the instance variables?) • What would those objects know? (i.e. what are the methods?)

  4. Our zoo • In order to not duplicate lots of information that is shared by our data, could we maybe set up a hierarchy of objects similar to the Taxonomy that we’ve learned about in Biology class???? Animal Reptile Mammal Please Java, can we?? Canine Primate Wolf Dog

  5. Of course we can… we just need some Inheritance

  6. Inheritance • Inheritance to the rescue! • We can describe higher level objects (like Animal or Mammal) and have characteristics (or actions) defined there that are true for any object beneath it in the hierarchy • This saves us from repeating tons of code! • The high level class is the parent class (aka superclass or base class) • The derived (lower level) classes is the child class (aka subclass)

  7. Inheritance • Form of software reuse in which classes are created by absorbing an existing class’s data and methods • Which you can embellish with new or modified capabilities • Allows you to define a very general class and later define more specialized classes by adding new details

  8. So you have a hierarchical relationship -- now what?? • You must define the Superclass: public class Animal{ String name; int size; public void eat(){ //do something } } • Then you define the the Subclass, which needs to extend the Superclass (using the Java keyword extends). The subclass has everything in the superclass, plus anything else you want to add! public class Dog extends Animal{ public void bark(){ //do something } } • Note: if fido is an object of type Dog, you can call fido.eat() and java will recognize the method as valid

  9. IS-A Relationship • Inheritance is always an IS-A relationship • To make sure you are designing your classes properly and making use of inheritance, ask yourself: • Does SubClass IS-A Superclass make sense? • Does Dog IS-A Animal make sense? • Does Janitor IS-A Employee make sense? • Does Triangle IS-A ThreeDimensionalShape make sense?

  10. Designing with Inheritance • Make sure you think out the relationships between all the objects and what makes sense • Practice Abstraction • Focus on the big picture and commonalities between objects, rather than on implementation details

  11. Another Sample Hierarchy Shape ThreeDimensionalShape TwoDimensionalShape Sphere Tetrahedron Triangle Circle Square Cube

  12. Book Example (From Ch 8) • Book • protected int pages = 1500; • setPages(int numPages) • int getPages() • Dictionary (is-a Book) • int definitions = 52500; • Double computRatio() • setDefintions(int numDefinitions) • getDefintions() public class Words{ Dictionary webster = new Dictionary(); webster.getPages(); webster.getDefinitions(); webster.computeRatio(); }

  13. How it works • The Book code is needed to create the definition of Dictionary, but we never need a Book object • Inheritance is a one-way street • Dictionary can use methods/variables of Book, but not the other way around

  14. What is the protected qualifier? • The protected keyword is the best encapsulation that still permits inheritance • If a superclass declares its data or methods protected it means that any subclasses can access the data • It also means that any thing in that package can also access the data • Private superclass members can only be changed by a subclass by using non-private accessor methods

  15. Methods in the Superclass • The Superclass can define methods and indicate data that all the Subclasses should have • But what if the subclass wants to behave differently than the superclass • It can override the superclass’s method • Overriding is kind of like overloading • What do you think the difference is?

  16. Overloading public class myClass{ public myClass(){ } public myClass(int x, int y){ } public void move(){ } public void move(int x){ } } Overloading = Two methods with the same name, But different method signatures

  17. Overriding • Superclass has a method: public void rotate(){ System.out.println(“Spin Right”); } • Subclass wants to redefine method: public void rotate(){ System.out.println(“Spin Left”); } Overriding = Method with the same name But different functionality in a superClass and subClass

  18. Overriding • We’ve already been using Overriding! • Every class in Java extends from java.lang.Object • This class defines a toString method (which by default returns the internal representation of the object) • When we make our toString methods, we override the default version and return something more meaningful • What do we do if we want to use part of the superclass’s method (or part of its constructor)? • Use the super reference

  19. The super reference • The super reference refers to an object’s direct superclass (one level up in the hierarchy tree) • super() refers to the Superclass’s constructor • super.doStuff() would refer to the Superclass’s doStuff method • super.x would refer to the Superclass’s variable named x (assuming a protected variable)

  20. Constructors in inheritance • Constructors are not inherited from the superclass at all. • If you want to access the superclass constructors, you must use super()

  21. A little example class Animal { String name; String noise; public Animal(String name, String noise){ this.name = name; this.noise = noise; } public void move (){ System.out.println(“Moving”); } public void eat (){ System.out.println(“Dinner Time”); } }

  22. A little example class Dog extends Animal { int mySize; public Dog(String name, String noise, int size){ super(name,noise); mySize = size; } public Dog(){ super(“Fido”, “Woof”); } public void move (){ System.out.println(“Walking”); } }

  23. Inheritance Lab • Exercise 8.2: Design and implement a set of classes that defines the employees of a hospital: doctor, nurse, administrator, surgeon, receptionist, janitor, and so on. Include methods in each class that are named according to the services provided by that person and that print an appropriate message. Create a main driver class to instantiate and exercise several of the classes. • Before you start programming, please show me the hierarchy of objects that you plan on using.

  24. APCS-A: Java Abstract Classes and Interfaces November 29, 2005

  25. Checkpoint • Hospital employee Lab • Java Quiz 2 Questions?

  26. Abstract Classes • A ghost class - it can pass along methods and variables but it can’t be instantiated • Animal class is good for inheritance, but we can’t really have a generic Animal object • So restrict it by declaring it an abstract class • Inheritance still works, so the subclasses still benefit from the Animal definition, we’re just enforcing the fact that you can’t create an object of type Animal

  27. Concrete Classes • When you are designing inheritance structure – some classes are specific enough to be instantiated • These are the concrete ones

  28. Abstract Methods • If a method must be overriden – make it abstract • You’ll get a compile time error if you don’t write the method in the subclass • An abstract method has no body, it exists only as a contract (details what is common to all subclasses) • The first concrete class in the inheritance tree must implement all abstract methods • An abstract method has to be in an abstract class (but that class can contain non-abstract methods as well)

  29. Interfaces • An Interface is a 100% abstract class, it can’t be instantiated • It’s a collection of variables and abstract methods • Another contract that objects can fulfill - allows us to know what methods are available in a given class • Let’s explore this a little more to see why it is necessary

  30. Digital Recorder burn() CDBurner burn() DVDBurner burn() ComboDrive Two superclasses? • Why do you think we have interfaces instead of having the base class extend two superclasses? • (Why can multiple inheritance be a bad thing?)

  31. Multiple Inheritance • Leads to ambiguity • “The Deadly Diamond of Death” • In our example: which burn method would ComboDrive inherit? • Don’t want the language to have to support/encode special rules to deal with ambiguity • Ambiguity is bad in programming!

  32. And therefore • Java has interfaces instead of multiple inheritance • Gives you the benefits of multiple inheritance without ever putting you in the situation of the Deadly Diamond of Death • All methods in an interface are abstract • Nothing is inherited, the subclass must implement the methods and the JVM will never get confused about which version of an inherited method it was supposed to call

  33. Another interface benefit • You can now have classes from different inheritance trees implement the same interface Pet Animal Robot Canine Feline Agent RoboDog Dog Wolf Cat Lion

  34. Using an Interface • The keyword for interface is implements Dog extends Animal implements Pet • A class implements an interface by actually providing the code for all the abstract methods

  35. Interfaces in JavaAPI • Comparable • Iterator • List • Collection • EventListener • ErrorHandler • And on and on and on • (They’re listed in italics in the API docs)

  36. Comparable Interface • Why it is cool: • Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort) • What is has: • One method: compareTo, which takes an Object as a parameter and returns an integer: • Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. • How to use it: if(dog1.compareTo(dog2) < 0) System.out.println(“dog1 is less than dog2”);

  37. Implementing Comparable public class Dog implements Comparable{ String name; int size; public Dog(String name, int size){ this.name = name; this.size = size; } public int getSize(){ return size; } public int compareTo(Object o){ if(o instanceOf Dog){ int otherDogSize = ((Dog) o).getSize(); return this.size- otherDogSize; } else return -1; // if we don't get a Dog, we'll say that we are less than the object we got } }

  38. Lab/Homework • Sample AP Free Response Question on arrays • You need to program an entire working example - so you will need to also implement a constructor and the hallIsClear() method • In the constructor you need to set default values for the 3 instance variables • Use this as a way to set up an initial problem to be solved • Also have a showMove(int moveNum) method that prints the current move number, the array and the carat showing the robots position and direction, clearHall() should call showMove after each move

  39. APCS-A: Java Polymorphism November 30, 2005

  40. SideNote • I may have misspoke the other day when I talked about Interfaces • You do not need to declare that Interface methods are abstract • A method declaration within an interface is followed by a semicolon (;) because an interface does not provide implementations for the methods declared within it. • All methods declared in an interface are implicitly public and abstract.

  41. Polymorphism • If we say that every class in Java extends (inherits) from Object, that means that everything IS-A Object. • Inheritance allows us to use the more general category to refer to all the subclasses. • Use the generic superclass Animal to refer to all the different animal subclasses • This allows you to have really flexible code • Its cleaner, more efficient, easier to develop & easier to extend! • Polymorphism means “having many forms”

  42. In the world before inheritance • We declared a reference variable • Dog myDog; • We created the object and assigned it to the reference • myDog = new Dog(); • Or in one step: Dog myDog = new Dog(); • And the reference type and the object were the same (they were both Dogs)

  43. Now… • With polymorphism, the reference type and the object type can be different • Animal myDog = new Dog(); • The reference type can be a superclass of the actual object type (any of the superclasses) • Object myDog = new Dog();

  44. Some code Animal [] animals = new Animal[5]; animals[0] = new Dog(); animals[1] = new Cat(); animals[2] = new Wolf(); animals[3] = new Hippo(); animals[4] = new Lion(); for(int i=0; i<animals.length; i++){ animals[i].eat(); animals[i].move(); }

  45. What it does animals[i].eat(); animals[i].move(); • When i is 0, we have a Dog and the Dog’s eat() method is called, but when i is 1, we have a Cat and the Cat’s eat method is called • This works for any of the Animal-class methods • The process of deciding which method (i.e. from which object) to use at run time is called dynamic (or late) binding

  46. What it means • Write code using polymorphic arguments, declare the method parameter as a superclass type – then you can pass in any subclass object at runtime • So you can write your code, pass it off to someone else, and they can add all the new subclass types – your methods will still work

  47. Rules for overriding • When you override a method, you are agreeing to fulfill the contract (the method specification) • Return type and parameters (number and type) need to be exactly the same as the overridden method in the superclass • The method can’t be less accessible (but it can be more) • So the subclass method can’t be private if the superclass method was public

  48. Polymorphism in action • The Java Library is bursting with polymorphism • Tons of methods with generic and abstract arguments and return types • Collections, classes, & methods in the library work with all the classes you create (classes that the creators of Java had no idea you were going to write!) • Because everything is an Object (there is an implicit extension)

  49. What’s in Object class? • “Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.” • The mega superclass has: • boolean equals() • Class getClass() • int hashCode() • String toString() • Object clone() • And more…

  50. Other Stuff

More Related