1 / 31

Inheritance, polymorphism & typing rules in Java – revision

Inheritance, polymorphism & typing rules in Java – revision. or: Everything you wanted to know about OOP but were afraid to ask. SOFTENG 251 Object Oriented Software Construction. Who I am. Hong Yul Yang PhD candidate (another one) Software Engineering alumni 2000 – 2003

iliana
Télécharger la présentation

Inheritance, polymorphism & typing rules in Java – revision

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. Inheritance, polymorphism & typing rules in Java – revision or: Everything you wanted to know about OOP but were afraid to ask SOFTENG 251 Object Oriented Software Construction

  2. Who I am • Hong Yul Yang • PhD candidate (another one) • Software Engineering alumni 2000 – 2003 • Yes, I was just like you when I was, erm, younger • Tutored for SoftEng courses (for a long time) • Teaching stance: • I’m learning from you just as much as you’re learning from me! • Tell me how you’re finding the material • How to contact me: room 303.476; “open” door hours; email( hongyul@cs.auckland.ac.nz ) SOFTENG 251 Object Oriented Software Construction

  3. Building 303, Room 476 476 Level 4 Me Elevators SOFTENG 251 Object Oriented Software Construction

  4. Today is a catch-up lecture (no Generics yet) Are you really comfortable with the fundamental OOP (Object-oriented programming) concepts? Inheritance Polymorphism & dynamic binding Typing rules: really, what can a variable point to? Interfaces & abstract classes I need to know what you don’t know I’m going to go slow til you get ‘em What’s bothering you? SOFTENG 251 Object Oriented Software Construction

  5. Assumptions • You are comfortable enough with object-based programming • i.e. C – structs + objects • You know • How to write classes and define methods • How to instantiate objects of a certain class • How to invoke methods of an object • The difference between instance and static variables/methods • Basically part A of the assignment is under your grasp • Uhh, right? SOFTENG 251 Object Oriented Software Construction

  6. Inheritance public class Animal (extends Object) • HumanextendsMammal • i.e. Mammal is a superclass (aka parent) of Human • What does this mean? • Human ‘is a’Mammal – but the opposite isn’t necessarily true! • Everything a Mammal does (methods) and have (instance variables), a Human can too – but again the opposite isn’t necessarily true! • Human also extendsAnimal, thus repeat above with Animal public class Mammal extends Animal public class Human extends Mammal Object Animal Mammal Bird Cat Dog Human SOFTENG 251 Object Oriented Software Construction

  7. Animal public class Animal { private int age = 0; public Animal() { System.out.println("animal born"); } public void makeSound() { System.out.println("gibberish"); } public void getOlder(int years) { age += years; } public int getAge() { return age; } } Animal -age +makeSound() +getOlder() +getAge() Animal animal = new Animal(); animal.getOlder(2); System.out.println(animal.getAge()); animal.makeSound(); SOFTENG 251 Object Oriented Software Construction

  8. Mammal Animal -age public class Mammal extends Animal{ protected String name; public Mammal(String name) { this.name = name; } public void makeSound() { System.out.print(name+" goes: "); super.makeSound(); } } • Every constructor must first call a constructor from its superclass • If it doesn’t, then Java implicitly calls an empty super-constructor:super() • protected means visible only to subclasses (and classes within same package) +makeSound() +getOlder() +getAge() overriding Mammal super is a special ‘variable’ #name +makeSound() Mammal mammal = new Mammal("Bambi"); mammal.getOlder(1); System.out.println(mammal.getAge()); mammal.makeSound(); SOFTENG 251 Object Oriented Software Construction

  9. Bird Animal -age public class Bird extends Animal { private int age = 10; public void fly() { System.out.println("Don't look down"); } public int getAge() { return age; } } ?? +makeSound() +getOlder() +getAge() overriding Mammal Bird #name -age • If you don’t define a constructor, Java implicitly defines an empty constructor, which in turn calls an empty super-constructor • Fields are not overridden, i.e. they belong exclusively to their enclosing class +makeSound() +fly() +getAge() Mammal mammal = new Mammal("Bambi"); Bird bird = new Bird(); Bird.getOlder(5); System.out.println(bird.getAge()); bird.makeSound(); mammal.fly(); //?? bird.fly(); SOFTENG 251 Object Oriented Software Construction

  10. Human Animal -age public class Human extends Mammal { public Human(String name) { super(name); } public void makeSound() { int myAge = age; myAge = getAge(); System.out.println("I'm " + name + " and " + myAge + " years old"); } public String lie() { return "I like you"; } } Explicit super-constructor +makeSound() +getOlder() +getAge() ?? Mammal Bird #name -age +makeSound() +fly() +getAge() protected access Animal animal = new Animal(); Human human = new Human("Hong"); human.getOlder(3); human.makeSound(); animal.lie(); //?? human.lie(); Human +makeSound() +lie() SOFTENG 251 Object Oriented Software Construction

  11. Polymorphism Animal • Recall: • Human ‘is a’ Mammal • Everything a Mammal does (methods) and have (instance variables), a Human can too • Similarly, Mammal ‘is an’ Animal. thusHuman ‘is an’ Animal -age +makeSound() +getOlder() +getAge() Human human = new Human("Hong"); Animal animalMan = human; animalMan.getOlder(10); animalMan.makeSound(); Animal animal = new Mammal("Whoa"); animal.makeSound(); Polymorphism right there Mammal #name +makeSound() • But the opposite isn’t necessarily true! Human Mammal noname = new Animal(); Animal animalMan = human; animalMan.lie(); +makeSound() +lie() SOFTENG 251 Object Oriented Software Construction

  12. Polymorphism Animal • Summary: • Variable vardeclared as type (class) Tcan point to any value declared asT or T’s subclass • Variable vardeclared as type T can access all visible methods defined in T as well as all of T’s superclasses • varcan’t point to any value declared as T’s superclass, even if the value’s actual type is T or T’s subclass • varcan’t access any method defined in T’s subclass, even if var’s actual type is T’s subclass -age +makeSound() +getOlder() +getAge() Mammal #name +makeSound() Human me = new Human(); Animal animal = new Animal(); Animal polymorph = me; Human me2 = polymorph; //ERR polymorph.lie(); //ERR Human polymorph’s declared type is Animal, although the actual type of the object it points to is of type Human +makeSound() +lie() SOFTENG 251 Object Oriented Software Construction

  13. Overriding & dynamic binding Animal • So we know what methods we can call; but how do we know which (overridden) method actually gets executed? -age +makeSound() +getOlder() +getAge() Human human = new Human("Hong"); Animal animalMan = human; animalMan.getOlder(10); animalMan.makeSound(); Animal animal = new Mammal("Whoa"); animal.makeSound(); Animal birdAnimal = bird; birdAnimal.getOlder(7);System.out.println(birdAnimal.getAge()); what happens here? and here? Bird Mammal -age #name +fly() +getAge() +makeSound() what about here? • Simple rule: • Depends on the actual type of the object the variable points to • Regardless of the declared type Human +makeSound() +lie() SOFTENG 251 Object Oriented Software Construction

  14. Back to typing rules • Every value has an associated type • "hi" is of type String • 23 is of type int • new Mammal("Grr") is of type Mammal • Every variable has a declared type, to which you can assign any value of type compatible with the declared type • double ratio = 0.22;ratio is declared as type double, and it holds a value of type double • double rounded = 235;rounded is declared as type double, but you can assign a value of type int to it. Why? int is essentially a “subtype” of double • What does compatible mean? Simple: X is compatble with Y if X = Y or X is a subtype of Y (for objects, subtype = subclass) SOFTENG 251 Object Oriented Software Construction

  15. To whom can you assign stuff? • Easy rule: • You can directly assign anything “up the hierarchy” • long = intdouble = longObject = MammalAnimal = HumanGeneral = Specific • Incompatible: • Mammal  Object • Bird  Dog double Object float Animal assign long Mammal Bird int Dog Human SOFTENG 251 Object Oriented Software Construction

  16. Different means of assignment Human dude = new Human("Orig"); Animal cloned = clone(dude); original = dude i.e. Mammal = Human cloned = “return value” i.e. Animal = Mammal public Mammal clone(Mammal original) { Human human = new Human("Ayee"); human.getOlder(original.getAge()); return human; } “return value” = human i.e. Mammal = Human SOFTENG 251 Object Oriented Software Construction

  17. Assinging “downstream” (downcasting) • You can’t do this for obvious reasons Animal animal = new Bird(); //ALLOWED Dog dog = animal; //NAH! Object • But what about: Animal animal = new Dog(); //ALLOWED Dog dog = animal; Animal ?? • Makes sense, but still not allowed by compiler.But this is: Mammal Bird Animal animal = new Dog(); Dog dog = (Dog)animal; //Downcasting • But be careful: Animal animal = new Bird(); Dog dog = (Dog)animal; Dog Human • The above compiles! (why?) SOFTENG 251 Object Oriented Software Construction

  18. Summary • So what do we get out of all this? Animal -age Mammal[] zoo = new Mammal[3]; zoo[0] = new Dog("Fido"); zoo[1] = new Cat("Mimi"); Human primate = new Human("Primate"); primate.getOlder(20); zoo[2] = primate; makeNoise(zoo); polymorphic assignments +makeSound() … polymorphic parameter-passing Mammal #name public void makeNoise(Animal[] animals) { for (int i = 0; i < animals.length; i++) { animals[i].makeSound(); } } +makeSound() dynamic method dispatch (binding) Dog Cat Human +makeSound() … +makeSound() … +makeSound() +lie() SOFTENG 251 Object Oriented Software Construction

  19. Animal -age +makeSound() +getOlder() +getAge() Motivations for using inheritance • Extending in the literal sense – specialisation without re-inventing the wheel Human Superman -strength +makeSound() +lie() +fly() +seeThrough() • Refactoring an existing design by extracting common traits Human Bird Mammal -age #name -age -age #name +makeSound() +getOlder() +getAge() +lie() +makeSound() +getOlder() +getAge() +fly() +makeSound() +getOlder() +getAge() • When you sense repetition among classes: refactor them into hierarchy! SOFTENG 251 Object Oriented Software Construction

  20. Abstract methods • Sometimes we want the general class to represent a common operation, but the details of the operation varies depending on subclasses • All animals must eat, but how they eat should depend solely on their exact species Animal public abstract class Mammal extends Animal { ... //does not override eat() } public abstract class Animal { ... public abstract void eat(); } -age +makeSound() +getOlder() +getAge()+eat() public class Bird extends Animal { ... public void eat() { //something different } } public class Human extends Mammal { ... public void eat() { System.out.println("Wine’n dine"); } } SOFTENG 251 Object Oriented Software Construction

  21. Abstract classes • Abstract methods are essentially “blank” methods that are up to subclasses to “fill in” (override) • If a class has one or more abstract methods, then it must be declared abstract • Naturally, you can’t instantiate an abstract class • But you can call abstract methods just as you call normal methods Animal a = new Bird(); a.eat(); //there • Also, if a subclass does not override all of the abstract methods of its superclass, then the subclass becomes an abstract class itself public abstract class Mammal extends Animal { ... //does not override eat() } SOFTENG 251 Object Oriented Software Construction

  22. Templating using abstract methods • Redefining Mammal’s makeSound() to be of the form: • <name> is <age> year(s) old and says to you: '<sound>' • name and age are “fixed” but <sound> varies according to specific subclass • See code demo SOFTENG 251 Object Oriented Software Construction

  23. Java Interfaces • Interfaces are special “classes” whose methods are all abstract • i.e. über-abstract classes if you will • One major distinction: a class can “extend” (implement) multiple interfaces • So what good is a “class” with no real methods? • Interfaces are useful for defining a “signature”, or a “contract” of its implementing classes • i.e. the methods in the interface define what the implementing class should do, i.e. expected to do • Also a “cheap” way of supporting multiple inheritance • Example: java.util.List is an interface that defines what a list is supposed to do, and ArrayList and LinkedList actually implement these contracts SOFTENG 251 Object Oriented Software Construction

  24. Flyer interface • All birds can fly – so can some mammals • But you can’t extend from both mammals and bird  introduce a Flyer interface public interface Flyer { public void fly(); } public class Bird extends Animal implements Flyer { public void fly() { System.out.println("Don’t look down"); } } Flyer <<interface>> +fly() Mammal public class FlyingSquirrel extends Mammal implements Flyer { public void fly() { System.out.println("Yay!!"); } } FlyingSquirrel Bird #name -age Flyer flyer = new FlyingSquirrel(); flyer.fly(); flyer = new Bird(); flyer.fly(); +fly() +makeSound() +fly() +getAge() SOFTENG 251 Object Oriented Software Construction

  25. More Interface facts • In a Java interface, you: • can only define public abstract methods(actually, even if it’s not explicitly declared public or abstract, Java automatically makes it so) • can’t define instance variables • can only define public, static and/or final variables • Rules of inheritance and polymorphism apply to interfaces just as they do to normal classes • e.g. an interface can inherit from another interface! public interface FastFlyer extends Flyer { public void hyperdrive(); } • Class implementing FastFlyer must implement both fly() and hyperdrive() SOFTENG 251 Object Oriented Software Construction

  26. Coming up… • Tutorial tomorrow? • Lab on Thursday [3rd April], 10am – 12pm • Assignment 1 due • Friday session [4th April]: Assignment 1 post-mortem • Can group 4 please see me before Friday to discuss your post-mortem? • Assignment 2 is out • Due 24th April (Week 7 after the break) • I’ll give you a brief demo soon SOFTENG 251 Object Oriented Software Construction

  27. Epilogue... aka auxiliary rambling

  28. Why OOP? Why Java? • Truth is: you can write anything in a procedural language (C) • Hell, you can write anything in assembly language • But you’d rather program in C than assembly right? Why? • Useful abstractions (statements, loops, functions, structs) • Object-oriented languages provide even further abstractions (classes, class hierarchy) that naturally map to concepts in the real world • Java is a great platform for appreciating the usefulness and power of OOP SOFTENG 251 Object Oriented Software Construction

  29. The truth about software development • The big bang approach to writing programs is sooo 60’s • Don’t even bother trying to get it right the first time • You are not the only one writing the program • Up to thousands of people can be working on the same system What does this mean? • You must always program with the future in mind • Is my code going to be easy to modify and extend? • You must always program with other programmers in mind • Can they understand my code? • Can even I understand my own code? SOFTENG 251 Object Oriented Software Construction

  30. So… • What makes a good program? • Easy to understand • Easy to extend and/or modify • Easily adaptable to other purposes (reusable) • Less likely to fail miserably because of a silly mistake (robust) • Etc, etc • Really, if we didn’t care about any of the above, we might as well write everything in machine code • I mean, it looks badass 1011010001010101010101110100100001001010110101 • But we’re not training you to be hackers! SOFTENG 251 Object Oriented Software Construction

  31. Java API classes = Good OOP • API = Application Programmers Interface • It’s really a collection of “programs” (aka library) with the sole purpose of being reused by Java programmers (aka you) • Notice how each class has a clearly defined role and purpose • String represents a sequence of characters and has operations (methods) for doing various nice things with it • Vector represents a growable list of items and has operations for manipulating the list • Classes from the Java API are no different from the classes you create  they aren’t anything special • Learn from them! SOFTENG 251 Object Oriented Software Construction

More Related