Single implementation inheritance.
- By Wm. Paul Rogers
- August 14, 2000
JAVA PRIMER
Objects Don't Polymorph: A Conceptual View of Subtype Polymorphism
Wm. Paul Rogers
Listing 1. Single implementation inheritance.
public class Base
{
public String m1()
{ return "Base m1"; }
public String m2()
{ return "Base m2"; }
public String m3()
{ return "Base m3"; }
}
public class Derived1
extends Base
{
public String m1()
{ return "Derived1 m1"; }
public String m4()
{ return "Derived1 m4"; }
}
public class Derived2
extends Derived1
{
public String m2()
{ return "Derived2 m2"; }
public String m5()
{ return "Derived2 m5"; }
}
// Elided
//
// Attach new Derived2 reference to new
// Derived2 object.
Derived2 derived2 = new Derived2();
// Attach new Base reference to existing
// Derived2 object.
Base base = derived2;
// Send m1 message through Derived1 and Base
// references. Object mapping to class method
// is unaffected by reference type.
derived2.m1(); // "Derived1 m1"
base.m1(); // "Derived1 m1"
// Send m2 message through Base reference.
// Derived2 object mapping is used.
base.m2(); // "Derived2 m2"
// Attach Base reference to new Derived1 object
base = new Derived1();
// Send m1 & m2 message through Base reference.
// Now using Derived1 mappings.
base.m1(); // "Derived1 m1"
base.m2(); // "Base m2"
// Attach Base reference to new Base object
base = new Base();
// Send m1 & m2 message through Base reference.
// Now using Base mappings.
base.m1(); // "Base m1"
base.m2(); // "Base m2"