Inheritance and Polymorphism Fall 2007 CS180 Definitions - - PDF document
Inheritance and Polymorphism Fall 2007 CS180 Definitions - - PDF document
Inheritance and Polymorphism Fall 2007 CS180 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
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
– Common error: if you don’t call super explicitly, make sure your superclass has a default constructor!
- Must be first line of 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 re- write 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 add1() { bump(); } private void bump() { x++; } } public class B extends A { public B() { super(); } public B(int x) { super(x); } public void add1() { set(get()+1); } }
Inheriting From the Superclass
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 add1() { bump(); } private void bump() { x++; } } public class B extends A { public B() { super(); } public B(int x) { super(x); } public void add1() { set(get()+1); } } 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 add1() { bump(); } private void bump() { x++; } } public class B extends A { public B() { super(); } public B(int x) { super(x); } }
The add1() method is overridden here!
Inheriting From the Superclass
public class A { A() { SOP(“A”); } } public class B extends A { public B() { SOP(“B”); } } public class C extends A { public C() { SOP(“C”); } } public class D extends B { public D() { SOP(“D”); } }
A = new A(); Output: A B = new B(); Output: AB C = new C(); Output: AC D = new D(); Output: ABD
On the superclass constructor calls, constructors wind up being executed top-down on the hierarchy.
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
- verwritten
- equals – for comparisons (defaults to reference address
comparision)
- toString – 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(); // legal! All animals make sounds! a.fly(); // illegal! Not all animals know how to fly! ((Bat)a).fly(); // legal! A bat knows how to fly! ((Giraffe)a).gallop(); // 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++; } }
A a = new B(); a.bump(); SOP(“a=“+a.get());
Object a is of static type A, dynamic type B. On a method call, use dynamic type first!
static type dynamic type
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.getClass().equals(A.class) – true if x is an instance of class
A
- A.class.isAssignableFrom(x.getClass()) 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, compareTo, 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 doStuff(); } public interface J extends I { public void doMoreStuff(); } public interface K { public void doEvenMoreStuff(); } public class A implements J, K { public void doStuff() {…} public void doMoreStuff() {…} public void doEvenMoreStuff {…} } J extends I, so interface J actually has 2 methods: doStuff() and doMoreStuff(). 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 Mammal Fish Owl Bat Penguin Giraffe 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();