//Chapter 9 inheritance stuff crammed into here //part 2 public class Inheritance2 { public static void main( String[] args ) { X x1 = new X(); Y y1 = new Y(); System.out.println( "x1.i= " + x1.i ); System.out.println( "y1.i= " + y1.i ); //i inherited from X //System.out.println( "x1.j= " + x1.j ); //syntax error: X has no j System.out.println( "y1.j= " + y1.j ); x1.m1(); y1.m1(); //m1() inherited from X y1.m2(); //added to Y } } //super class is more general. class X { int i=3; void m1() { System.out.println( "hello from X m1()" ); } } //subclass is more specific, specialized. Extends the superclass. //subclass inherits members of superclass (and all ancestors back to Object). //subclass is customized with additional members (fields and methods) and //by overriding (redefining) superclass methods. //subclass is everything the superclass is, plus more. class Y extends X { int j=4; //field added to subclass Y. not in superclass X void m2() { System.out.println( "hello from Y m2()" ); } } //inheritance (IS-A): form of software reuse: new subclass gets all the data and //methods of superclass without duplicating code. // share common code (data and methods) among the instances of related classes. //composition (HAS-A): form of software reuse too. //can derive a subclass without access to superclass's source code. //thus can tweak or embellish existing wheel functionality without having to //reinvent the entire wheel.