void showij() { System.out.println("i and j: " + i + " " + j); }}
// Create a subclass by extending class A. class B extends A { int k;
void showk() {
System.out.println("k: " + k); } void sum() {
System.out.println("i+j+k: " + (i+j+k)); } }
class SimpleInheritance {
public static void main(String args[]) { A superOb = new A(); B subOb = new B();
// The superclass may be used by itself. superOb.i = 10; superOb.j = 20; System.out.println("Contents of superOb: "); superOb.showij(); System.out.println();
/* The subclass has access to all public members of
its superclass. */ subOb.i = 7; subOb.j = 8; subOb.k = 9; System.out.println("Contents of subOb: "); subOb.showij();subOb.showk(); System.out.println();
System.out.println("Sum of i, j and k in subOb:"); subOb.sum(); } }
public static void main(String args[]) { BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3); BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076); double vol;
vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); System.out.println("Weight of mybox1 is " + mybox1.weight); System.out.println();
vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); System.out.println("Weight of mybox2 is " + mybox2.weight);
} }
该程序的输出显示如下:
Volume of mybox1 is 3000.0 Weight of mybox1 is 34.3
Volume of mybox2 is 24.0 Weight of mybox2 is 0.076
public static void main(String args[]) { BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37); Box plainbox = new Box(); double vol;
vol = weightbox.volume(); System.out.println("Volume of weightbox is " + vol); System.out.println("Weight of weightbox is " +
weightbox.weight); System.out.println(); // assign BoxWeight reference to Box reference
plainbox = weightbox;
vol = plainbox.volume(); // OK, volume() defined in Box
System.out.println("Volume of plainbox is " + vol);
/* The following statement is invalid because plainbox does not define a weight member. */ // System.out.println("Weight of plainbox is " + plainbox.weight); }}