Inheritance & Polymorphism Android Club 2015
Agenda Inheritance Polymorphism
WHY to use inheritance? CODE REUSE
Inheritance
Inheritance: example public class Bike { int wheel; public Bike() { this.wheel = 2; } public int getWheel() { return wheel; } public void setWheel(int wheel) { this.wheel = wheel; } }
Inheritance: example public class MountainBike extends Bike{ public MountainBike() { super(); }
Inheritance: example public class KidBike extends Bike{ public KidBike() { setWheel(3); }
Inheritance: practice Create super class: Transport Create variables: int wheel + getter&setter Default wheels number should be 4 Create sub-class: Car Create Car constructor: inside call Transport constructor Create sub-class: Boat Set wheel 0
Polymorphism Two objects respond to the same message with different behaviors; the sender doesn't have to care. Steven A. Lowe Peter Mortensen
Polymorphism There are: 2 objects Message: makeNoise Cat: meow Dog: wow Sender does not care
Polymorphism: Animal public class Animal { public String getNoise() { return null; }
Polymorphism: Cat public class Cat extends Animal{ public String getNoise() { return "Meow"; }
Polymorphism: Dog public class Dog extends Animal{ public String getNoise() { return "Wow"; }
Polymorphism: main Animal animal1 = new Cat(); System.out.println(animal1.getNoise()); Animal animal2 = new Dog(); System.out.println(animal2.getNoise());
Polymorphism: practice Create super-class: Zombie Create method: eat Return: void
Polymorphism: practice Create sub class: GardenZombie Create method: eat “Eats 5 pieces”
Polymorphism: practice Create sub class: Gargantua Create method: eat Print “Eats 10 pieces”
Polymorphism: practice Declare Zombie zombieOne Initialize it as GardenZombie Make zombieOne eat Declare Zombie: zombieTwo Initialize it as Gargantua Make zombieTwo eat
Questions? Any questions?
Review Chapter 10: Working with Inheritance and Polymorphism Interface
Thank you! Thank you very much for your attention!