inheritance, polymorphism & typing rules in java – revision softeng 251 object oriented...
TRANSCRIPT
Inheritance, polymorphism & typing rules in Java – revision
SOFTENG 251
Object Oriented Software Construction
or: Everything you wanted to know about OOP but were afraid to ask
SOFTENG 251 Object Oriented Software Construction 2OOP in 60 minutes
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( [email protected] )
SOFTENG 251 Object Oriented Software Construction 3OOP in 60 minutes
Building 303, Room 476
Level 4 Me
476
Elevators
SOFTENG 251 Object Oriented Software Construction 4OOP in 60 minutes
What’s bothering you?
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
SOFTENG 251 Object Oriented Software Construction 5OOP in 60 minutes
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 6OOP in 60 minutes
Inheritance
Human extends Mammal 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 extends Animal, thus repeat above with Animal
Animal
Mammal Bird
Cat Dog Human
Object
public class Human extends Mammal
public class Mammal extends Animal
public class Animal (extends Object)
SOFTENG 251 Object Oriented Software Construction 7OOP in 60 minutes
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
+makeSound()+getOlder()+getAge()
-age
Animal animal = new Animal();animal.getOlder(2);System.out.println(animal.getAge());animal.makeSound();
SOFTENG 251 Object Oriented Software Construction 8OOP in 60 minutes
Mammalpublic class Mammal extends Animal{ protected String name; public Mammal(String name) { this.name = name; } public void makeSound() { System.out.print(name+" goes: "); super.makeSound(); }} Mammal
+makeSound()
#name
Animal
+makeSound()+getOlder()+getAge()
-age
Mammal mammal = new Mammal("Bambi");mammal.getOlder(1);System.out.println(mammal.getAge());mammal.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)
overriding
super is a special ‘variable’
SOFTENG 251 Object Oriented Software Construction 9OOP in 60 minutes
Bird
Mammal
+makeSound()
#name
Bird
+fly()+getAge()
-age
Animal
+makeSound()+getOlder()+getAge()
-agepublic class Bird extends Animal { private int age = 10; public void fly() { System.out.println("Don't look down"); } public int getAge() { return age; }}
Mammal mammal = new Mammal("Bambi");Bird bird = new Bird();Bird.getOlder(5);System.out.println(bird.getAge());bird.makeSound();mammal.fly(); //??bird.fly();
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
??
overriding
SOFTENG 251 Object Oriented Software Construction 10OOP in 60 minutes
Human
Mammal
+makeSound()
#name
Bird
+fly()+getAge()
-age
Animal
+makeSound()+getOlder()+getAge()
-agepublic 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"; }}
Human
+makeSound()+lie()
??
protected access
Animal animal = new Animal();Human human = new Human("Hong");human.getOlder(3);human.makeSound();animal.lie(); //??human.lie();
Explicit super-constructor
SOFTENG 251 Object Oriented Software Construction 11OOP in 60 minutes
Polymorphism Recall:
Human ‘is a’ Mammal
Everything a Mammal does (methods) and have (instance variables), a Human can too
Similarly, Mammal ‘is an’ Animal. thus Human ‘is an’ Animal
Mammal
+makeSound()
#name
Animal
+makeSound()+getOlder()+getAge()
-age
Human
+makeSound()+lie()
Human human = new Human("Hong");Animal animalMan = human;animalMan.getOlder(10);animalMan.makeSound();Animal animal = new Mammal("Whoa");animal.makeSound();
Polymorphism right there
But the opposite isn’t necessarily true!
Mammal noname = new Animal();Animal animalMan = human;animalMan.lie();
SOFTENG 251 Object Oriented Software Construction 12OOP in 60 minutes
Polymorphism
Summary: Variable var declared as type (class) T can point to any
value declared as T or T’s subclass
Variable var declared as type T can access all visible methods defined in T as well as all of T’s superclasses
var can’t point to any value declared as T’s superclass, even if the value’s actual type is T or T’s subclass
var can’t access any method defined in T’s subclass, even if var’s actual type is T’s subclass
Human me = new Human();Animal animal = new Animal();Animal polymorph = me;
Human me2 = polymorph; //ERRpolymorph.lie(); //ERR
Mammal
+makeSound()
#name
Animal
+makeSound()+getOlder()+getAge()
-age
Human
+makeSound()+lie()
polymorph’s declared type is Animal, although the actual
type of the object it points to is of type Human
SOFTENG 251 Object Oriented Software Construction 13OOP in 60 minutes
Overriding & dynamic binding So we know what methods we can call; but how do we
know which (overridden) method actually gets executed?
Mammal
+makeSound()
#name
Animal
+makeSound()+getOlder()+getAge()
-age
Human
+makeSound()+lie()
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?
Simple rule: Depends on the actual type of the object
the variable points to
Regardless of the declared type
Bird
+fly()+getAge()
-age
what about here?
SOFTENG 251 Object Oriented Software Construction 14OOP in 60 minutes
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 15OOP in 60 minutes
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
float
long
int
assignAnimal
Mammal Bird
Dog Human
Object
SOFTENG 251 Object Oriented Software Construction 16OOP in 60 minutes
Different means of assignment
Human dude = new Human("Orig");
Animal cloned = clone(dude);
public Mammal clone(Mammal original) {
Human human = new Human("Ayee"); human.getOlder(original.getAge());
return human;}
original = dudei.e. Mammal = Human
“return value” = humani.e. Mammal = Human
cloned = “return value”i.e. Animal = Mammal
SOFTENG 251 Object Oriented Software Construction 17OOP in 60 minutes
Assinging “downstream” (downcasting) You can’t do this for obvious reasons
??Animal
Mammal Bird
Dog Human
ObjectAnimal animal = new Bird(); //ALLOWEDDog dog = animal; //NAH!
But what about:
Animal animal = new Dog(); //ALLOWEDDog dog = animal;
Makes sense, but still not allowed by compiler.But this is:
Animal animal = new Dog();Dog dog = (Dog)animal; //Downcasting
But be careful:
Animal animal = new Bird();Dog dog = (Dog)animal;
The above compiles! (why?)
SOFTENG 251 Object Oriented Software Construction 18OOP in 60 minutes
Summary
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); Mammal
+makeSound()
#name
Animal
+makeSound()…
-age
Human
+makeSound()+lie()
So what do we get out of all this?
Cat
+makeSound()…
Dog
+makeSound()…
polymorphic assignments
public void makeNoise(Animal[] animals) { for (int i = 0; i < animals.length; i++) { animals[i].makeSound(); }}
dynamic method dispatch (binding)
polymorphic parameter-passing
SOFTENG 251 Object Oriented Software Construction 19OOP in 60 minutes
Motivations for using inheritance
Extending in the literal sense – specialisation without re-inventing the wheel
Human
+makeSound()+lie()
Superman
+fly()+seeThrough()
-strength
Refactoring an existing design by extracting common traits
Mammal
+makeSound()+getOlder()+getAge()
-age#name
Human
+makeSound()+getOlder()+getAge()+lie()
-age#name
Bird
+makeSound()+getOlder()+getAge()+fly()
-age
Animal
+makeSound()+getOlder()+getAge()
-age
When you sense repetition among classes: refactor them into hierarchy!
SOFTENG 251 Object Oriented Software Construction 20OOP in 60 minutes
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
+makeSound()+getOlder()+getAge()+eat()
-agepublic abstract class Animal { ... public abstract void eat();}
public abstract class Mammalextends Animal { ... //does not override eat()}
public class Human extends Mammal { ... public void eat() { System.out.println("Wine’n dine"); }}
public class Bird extends Animal { ... public void eat() { //something different }}
SOFTENG 251 Object Oriented Software Construction 21OOP in 60 minutes
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
public abstract class Mammalextends Animal { ... //does not override eat()}
Also, if a subclass does not override all of the abstract methods of its superclass, then the subclass becomes an abstract class itself
SOFTENG 251 Object Oriented Software Construction 22OOP in 60 minutes
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 23OOP in 60 minutes
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 24OOP in 60 minutes
Flyer interface All birds can fly – so can some mammals
But you can’t extend from both mammals and bird introduce a Flyer interface
Flyer<<interface>>
+fly()
public interface Flyer { public void fly();}
public class FlyingSquirrel extends Mammalimplements Flyer { public void fly() { System.out.println("Yay!!"); }}
public class Bird extends Animalimplements Flyer { public void fly() { System.out.println("Don’t look down"); }}
Bird
+fly()+getAge()
-age
FlyingSquirrel
+fly()+makeSound()
#name
Mammal
Flyer flyer = new FlyingSquirrel();flyer.fly();flyer = new Bird();flyer.fly();
SOFTENG 251 Object Oriented Software Construction 25OOP in 60 minutes
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 26OOP in 60 minutes
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
Epilogue...
aka auxiliary rambling
SOFTENG 251 Object Oriented Software Construction 28OOP in 60 minutes
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 29OOP in 60 minutes
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 30OOP in 60 minutes
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 31OOP in 60 minutes
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!