Using super to Call Superclass Constructors

A subclass can call a constructor method defined by its superclass by use of the following form of super

super(parameter-list);

  • parameter-list is defined by the constructor in the super class.
  • super(parameter-list) must be the first statement executed inside a subclass' constructor. 
Program Mainsuper.java


class Box {
  private double width;
  private double height;
  private double depth;

  Box(Box ob) { // pass object to constructor
    width = ob.width;
    height = ob.height;
    depth = ob.depth;
  }
  Box(double w, double h, double d) {
    width = w;
    height = h;
    depth = d;
  }
  double volume() {
    return width * height * depth;
  }
}
class BoxWeight extends Box {
  double weight; // weight of box
  BoxWeight(Box ob) { // pass object to constructor
    super(ob);
  }
}
public class Mainsuper
 {
  public static void main(String args[]) {
    Box mybox1 = new Box(20, 30, 25);
    BoxWeight myclone = new BoxWeight(mybox1);
    double vol;

    vol = mybox1.volume();
    System.out.println("Volume of mybox1 is " + vol);
  }
}

Here,BoxWeight() calls super() with the parametrized w,h and d .This causes the Box() constructor to be called ,Which initialize Width ,height,depth using these values.BoxWeight no longer initializes these values itself.if only needs to initilize the value unique to it weight .This leaves Box free to make these values private if desired . In the preceding example super() wa called with three arguments .since constructors can be overloaded ,super() can be called using any form defined by the super class.The constructor executed will be the one that matches the arguments.For example ,here is a complete implementation of BoxWeight that provides constructors for the various ways that a box can be constructed .In each case super() is called using the appropriate arguments .


Output 

G:\>javac Mainsuper.java
G:\>java Mainsuper
Volume of mybox1 is 15000.0


Using super to Call Superclass Constructors

0 comments:

Post a Comment

 

learn java programming Copyright © 2011-2012 | Powered by appsackel.org