inheritance and polymorphism
play

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


  1. Inheritance and Polymorphism Fall 2007 CS180

  2. 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

  3. 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

  4. Syntax • To extend a class, public class A { private int x; use the extends keyword public A() { set(0); } public A(int x) { set(x); } • The class will now public void set(int x) { this.x = x; } inherit all non-private public int get() { return x; } public void add1() { bump(); } characteristics of the private void bump() { x++; } superclass } – Do not have to re- public class B extends A { write methods which public B() { super(); } public B(int x) { super(x); } are the same public void add1() { set(get()+1); } – Can introduce new } methods and/or variables

  5. Inheriting From the Superclass public class A { public class A { protected int x; private int x; public A() { set(0); } public A() { set(0); } public A(int x) { set(x); } public A(int x) { set(x); } public void set(int x) { this.x = x; } public void set(int x) { this.x = x; } public int get() { return x; } public int get() { return x; } public void add1() { bump(); } public void add1() { bump(); } private void bump() { x++; } private void bump() { x++; } } } public class B extends A { public class B extends A { public B() { super(); } public B() { super(); } public B(int x) { super(x); } public B(int x) { super(x); } } public void add1() { set(get()+1); } } The add1() method is overridden here!

  6. Inheriting From the Superclass On the superclass constructor calls, constructors wind up being executed top-down on the hierarchy. public class A { A = new A(); A() { SOP(“A”); } Output: A } public class B extends A { B = new B(); public B() { SOP(“B”); } Output: AB } public class C extends A { C = new C(); public C() { SOP(“C”); } Output: AC } public class D extends B { D = new D(); public D() { SOP(“D”); } Output: ABD }

  7. 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) • toString – translates your object into an appropriate String (defaults to the reference address)

  8. Polymorphism public class Animal { • Allows a variable to protected int age; take on many forms public void eat() { SOP(“Yummy!”); } • A variable of type } Animal may point to public class Giraffe extends Animal { public Giraffe() { super(); } may different types of animals public void eat() { SOP(“Eating leaves!”); } public void gallop() { SOP(“Galloping away!”); } • Only methods scoped } within the variable public class Bat extends Animal { type are available public Bat() { super(); } – Not all animals fly, so public void eat() { SOP(“Drinking blood!”); } public void fly() { SOP(“Flapping wings!”); } even though an } Animal identifier may _____________________________________________ point to a Bat object, Animal a = new Bat(); you cannot call the a.eat(); // legal! All animals make sounds! fly() method directly 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!

  9. 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

  10. Dynamic Binding public class A { protected int x; public A() { set(0); } public A(int x) { set(x); } static type dynamic type public void set(int x) { this.x = x; } public int get() { return x; } public void bump() { x+=2; } A a = new B(); Object a is of static type A, } dynamic type B. On a method a.bump(); call, use dynamic type first! public class B extends A { SOP(“a=“+a.get()); public B() { super(); } public B(int x) { super(x); } public void bump() { x++; } }

  11. 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

  12. Abstract Classes • Sometimes a superclass public abstract class Animal { never needs to be protected int age; instantiated – you only public abstract void eat(); make instances of the } subclasses public abstract class Mammal { public Mammal() { super(); } • Make class abstract public abstract void eat(); – Cannot be instantiated // other mammal-like behavior… – May have some methods be } abstract public class Giraffe extends Mammal { – Is like a blueprint for public Giraffe() { super(); } subclasses, with methods public void eat() { SOP(“Eating leaves!”); } that need to be filled in }

  13. 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

  14. Interfaces public interface I { public void doStuff(); } J extends I, so interface J actually has 2 methods: public interface J extends I { doStuff() and doMoreStuff(). public void doMoreStuff(); } public interface K { public void doEvenMoreStuff(); } public class A implements J, K { public void doStuff() {…} A implements J and K, so A must have a method for public void doMoreStuff() {…} each method in the interfaces it implements. public void doEvenMoreStuff {…} }

  15. 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

  16. Animal (Planet?) Animal Bird Mammal Fish Owl Penguin Bat Giraffe Whale Shark Salmon

  17. 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 {…}

Recommend


More recommend