Inheritance and Polymorphism CS 180 Fall 2007 Definitions






















- Slides: 22
Inheritance and Polymorphism CS 180 Fall 2007
Definitions • Inheritance – object oriented way to form new classes from pre-existing ones – Superclass • The parent class • If class is final, cannot inherit from this class – Subclass • Class which inherits all non-private properties from the superclass • Generally a specific instance of a superclass • Polymorphism – a object can take many forms • Combining the two, can create subclasses with different properties
Inheriting From the Superclass • Two ways – Use the protected keyword instead of the private keyword • Variables and methods which are protected are accessible by the subclass, but not the world – Use public for methods to inherit, private for methods to not inherit and all variables • • • Variables no longer accessible directly in subclass Use accessors and mutators to grab and modify them Override methods as necessary – If a method is declared final, then it cannot be overridden in a subclass – Can indicate with @override • • Not required, but a good check Constructors – Not inherited! Must rewrite them – Use super keyword to call superconstructor from parent class • • Can only use super as first line of a constructor (much like this) If no superconstructor is explicitly called, then super() (the default superconstructor) is automatically called as the first line • Must be first line of constructor – • Common error: if you don’t call super explicitly, make sure your superclass has a default constructor! super keyword can also be used to call instances of methods from superclass
Syntax • To extend a class, use the extends keyword • The class will now inherit all non-private characteristics of the superclass – Do not have to rewrite methods which are the same – Can introduce new methods and/or variables public class A { private int x; public A() { set(0); } public A(int x) { set(x); } public void set(int x) { this. x = x; } public int get() { return x; } public void add 1() { bump(); } private void bump() { x++; } } public class B extends A { public B() { super(); } public B(int x) { super(x); } public void add 1() { set(get()+1); } }
Inheriting From the Superclass public class A { protected int x; public class A { private int x; public A() { set(0); } public A(int x) { set(x); } public void set(int x) { this. x = x; } public int get() { return x; } public void add 1() { bump(); } private void bump() { x++; } } public class B extends A { public B() { super(); } public B(int x) { super(x); } public void add 1() { set(get()+1); } } The add 1() method is overridden here!
Inheriting From the Superclass On the superclass constructor calls, constructors wind up being executed top-down on the hierarchy. public class A { A() { SOP(“A”); } } A = new A(); Output: A public class B extends A { public B() { SOP(“B”); } } B = new B(); Output: AB public class C extends A { public C() { SOP(“C”); } } C = new C(); Output: AC public class D extends B { public D() { SOP(“D”); } } D = new D(); Output: ABD
Object Class • Class Object is the superclass of all superclasses in Java – All classes defined implicitly inherit from Object if not explicitly extending from another class – Even if explicitly extending another class, that other class either extends from another class or implicitly extends from Object – Some useful methods which are commonly overwritten • equals – for comparisons (defaults to reference address comparision) • to. String – translates your object into an appropriate String (defaults to the reference address)
Polymorphism • Allows a variable to take on many forms • A variable of type Animal may point to may different types of animals • Only methods scoped within the variable type are available – Not all animals fly, so even though an Animal identifier may point to a Bat object, you cannot call the fly() method directly public class Animal { protected int age; public void eat() { SOP(“Yummy!”); } } public class Giraffe extends Animal { public Giraffe() { super(); } public void eat() { SOP(“Eating leaves!”); } public void gallop() { SOP(“Galloping away!”); } } public class Bat extends Animal { public Bat() { super(); } public void eat() { SOP(“Drinking blood!”); } public void fly() { SOP(“Flapping wings!”); } } _______________________ Animal a = new Bat(); a. eat(); a. fly(); ((Bat)a). fly(); ((Giraffe)a). gallop(); // legal! All animals make sounds! // illegal! Not all animals know how to fly! // legal! A bat knows how to fly! // compiles, but runtime error!
Dynamic Binding • On the call the eat(), what happens? – If Animal object a is a Giraffe, then “Eating leaves!” – If Animal object a is a Bat, then “Drinking blood!” – Why not “Yummy!”? dynamic binding! • Objects have two types – Static type – the type of the variable name – Dynamic type – the “actual type” of the variable in memory • Dynamic binding – Resolved at runtime – Used for method lookup – Look up “most specific” instance of method call (look up the method in the dynamic type if it exists) – Most specific instance of a method may be in a parent class (and therefore inherited) • Static binding (optional) – Resolved at compile time – Used for variable lookup – Also all static variables and methods are resolved during compilation
Dynamic Binding public class A { protected int x; public A() { set(0); } public A(int x) { set(x); } public void set(int x) { this. x = x; } public int get() { return x; } public void bump() { x+=2; } } public class B extends A { public B() { super(); } public B(int x) { super(x); } public void bump() { x++; } } static type dynamic type Object a is of static type A, A a = new B(); dynamic type B. On a method a. bump(); call, use dynamic type first! SOP(“a=“+a. get());
Determining Class Type • In order to access a method in a subclass from an object with a static type of the superclass, need to downcast – Downcasting is unsafe! Need to know that downcast is legal. – Use instanceof keyword or other methods • x instanceof A – true if x is an instance of class A or a subclass of A • x. get. Class(). equals(A. class) – true if x is an instance of class A • A. class. is. Assignable. From(x. get. Class()) is true if x is an instance of class A or a subclass of A
Abstract Classes • Sometimes a superclass never needs to be instantiated – you only make instances of the subclasses • Make class abstract – Cannot be instantiated – May have some methods be abstract – Is like a blueprint for subclasses, with methods that need to be filled in public abstract class Animal { protected int age; public abstract void eat(); } public abstract class Mammal { public Mammal() { super(); } public abstract void eat(); // other mammal-like behavior… } public class Giraffe extends Mammal { public Giraffe() { super(); } public void eat() { SOP(“Eating leaves!”); } }
Interfaces • • • Contains method headers Cannot instantiate interface Cannot have any non-final variables A class can implement many interfaces Interfaces can extend from each other Example: Comparable – Contains one method, compare. To, which takes two objects and compares them • Returns a negative number if less than • Returns 0 if equal to • Returns a positive number if greater than – Comparable is an interface and not an abstract class because not all things comparable are related • Numbers and people are both comparable, but have no reasonable relationship between them
Interfaces public interface I { public void do. Stuff(); } public interface J extends I { public void do. More. Stuff(); } J extends I, so interface J actually has 2 methods: do. Stuff() and do. More. Stuff(). public interface K { public void do. Even. More. Stuff(); } public class A implements J, K { public void do. Stuff() {…} public void do. More. Stuff() {…} public void do. Even. More. Stuff {…} } A implements J and K, so A must have a method for each method in the interfaces it implements.
Abstract Class vs. Interface • Abstract classes are blueprints, interfaces are contracts – Interface: “Here’s some methods. If your class implements this interface, you must provide an implementation of each method in the interface in the class. ” • • Method headers final variables A class can implement multiple interfaces Cannot instantiate – Abstract class: “Here’s a blueprint for a class. If your class extends this abstract class, you can use any functionality here and add onto it, but you must fill in what I have not. ” • • • Abstract method headers Methods Variables A class can extend only one class Cannot instantiate
Animal (Planet? ) Animal Bird Owl Mammal Penguin Bat Giraffe Fish Whale Shark Salmon
Animal (Planet? ) Our animals: public class Owl {…} public class Penguin {…} public class Bat {…} public class Giraffe {…} public class Whale {…} public class Shark {…} public class Salmon {…}
Animal (Planet? ) Create appropriate superclasses: public class Animal {…} public class Bird {…} public class Mammal {…} public class Fish {…} public class Owl {…} public class Penguin {…} public class Bat {…} public class Giraffe {…} public class Whale {…} public class Shark {…} public class Salmon {…}
Animal (Planet? ) Connect the hierarchy: public class Animal {…} public class Bird extends Animal {…} public class Mammal extends Animal {…} public class Fish extends Animal {…} public class Owl extends Bird {…} public class Penguin extends Bird {…} public class Bat extends Mammal {…} public class Giraffe extends Mammal {…} public class Whale extends Mammal {…} public class Shark extends Fish {…} public class Salmon extends Fish {…}
Animal (Planet? ) Add in appropriate interfaces at the highest levels: public class Animal {…} public class Bird extends Animal {…} public class Mammal extends Animal {…} public class Fish extends Animal implements Swimmer {…} public class Owl extends Bird implements Flyer {…} public class Penguin extends Bird {…} public class Bat extends Mammal implements Flyer {…} public class Giraffe extends Mammal {…} public class Whale extends Mammal implements Swimmer {…} public class Shark extends Fish {…} public class Salmon extends Fish {…}
Animal (Planet? ) Make appropriate classes abstract: abstract public class Animal {…} abstract public class Bird extends Animal {…} abstract public class Mammal extends Animal {…} abstract public class Fish extends Animal implements Swimmer {…} public class Owl extends Bird implements Flyer {…} public class Penguin extends Bird {…} public class Bat extends Mammal implements Flyer {…} public class Giraffe extends Mammal {…} public class Whale extends Mammal implements Swimmer {…} public class Shark extends Fish {…} public class Salmon extends Fish {…}
Animal (Planet? ) abstract public class Animal {…} abstract public class Bird extends Animal {…} abstract public class Mammal extends Animal {…} abstract public class Fish extends Animal implements Swimmer {…} public class Owl extends Bird implements Flyer {…} public class Penguin extends Bird {…} public class Bat extends Mammal implements Flyer {…} public class Giraffe extends Mammal {…} public class Whale extends Mammal implements Swimmer {…} public class Shark extends Fish {…} public class Salmon extends Fish {…} Which are valid instantiations? Animal a = new Animal(); Animal b = new Fish(); Animal c = new Flyer(); Mammal d = new Bat(); Fish e = new Swimmer(); Swimmer f = new Shark(); Flyer g = new Owl(); Swimmer h = new Whale(); Swimmer i = new Fish();