Week 10 Oct 29 Summary: 1. Inheritance allows (a) keeping common parts of CD/DVD code in one place (Item) [helps prevent Code Duplication in CD & DVD] (b) just a single list of Item, rather than separate CD/DVD lists [helps prevent Code Duplication in main class!] 2. "extends" keyword, use of super() to call superclass constructor 3. Base-class variable can be assigned derived-class objects: Item theItem = new CD(....); 4. Problem getting specific identity back: fixes: instanceof (painful) OOP magic: most-specific-method rule When base class and derived class both have same method, the more specific (derived-class) one is invoked ============================================================ inheritance demo public class Base { private int x; public Base(int x) { this.x = x; } public String foo() { return "All your BASE are belong to us!"; } public int bar( ) { return x; } } public class A extends Base { private int y; public A(int x, int y) { super(x); this.y = y; } public String foo() { return "I am an A"; } public int bar() { return super.bar() + y; } public int baz() { return 0xDEADBEEF; } } public class B extends Base { private int z; public B(int x, int y) { super(x); this.z = y; } public String foo() { return "BBBBBB>>>" + super.foo() + "<< picture; then we can draw each shape with for (MyShape s : picture) { s.draw(); } However, we *cannot* do this if we have three unrelated shape classes. The only class they have in common is Object. That's the only type that could hold all three. But it's too general to be able to draw()!