top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Java: What is the significance of creating Sub class object using super class reference?

+2 votes
413 views
Java: What is the significance of creating Sub class object using super class reference?
posted Jun 2, 2015 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

A Superclass Variable Can Reference a Subclass Object

class RefDemo {
  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();

    plainbox = weightbox;

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

  }
}

class Box {
  private double width;

  private double height;

  private double depth;

  Box(Box ob) { 
    width = ob.width;
    height = ob.height;
    depth = ob.depth;
  }

  Box(double w, double h, double d) {
    width = w;
    height = h;
    depth = d;
  }

  Box() {
    width = -1; 
    height = -1;
    depth = -1; 
  }

  Box(double len) {
    width = height = depth = len;
  }

  double volume() {
    return width * height * depth;
  }
}

class BoxWeight extends Box {
  double weight;

  BoxWeight(BoxWeight ob) { 
    super(ob);
    weight = ob.weight;
  }

  BoxWeight(double w, double h, double d, double m) {
    super(w, h, d); 
    weight = m;
  }

  BoxWeight() {
    super();
    weight = -1;
  }

  BoxWeight(double len, double m) {
    super(len);
    weight = m;
  }
}
answer Jun 25, 2015 by Karthick.c
...