Java Inheritance Reference a Superclass variable from a Subclass Object

Introduction

We can access variable from super class from a sub class.

The variable cannot be private.

// This program uses inheritance to extend LegoBlock.
class LegoBlock {
  double width;//from  www.ja  v a2  s.c o  m
  double height;
  double depth;

  // construct clone of an object
  LegoBlock(LegoBlock ob) { // pass object to constructor
    width = ob.width;
    height = ob.height;
    depth = ob.depth;
  }

  // constructor used when all dimensions specified
  LegoBlock(double w, double h, double d) {
    width = w;
    height = h;
    depth = d;
  }

  // constructor used when no dimensions specified
  LegoBlock() {
    width = -1;  // use -1 to indicate
    height = -1; // an uninitialized
    depth = -1;  // box
  }

  // constructor used when cube is created
  LegoBlock(double len) {
    width = height = depth = len;
  }

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

// Here, LegoBlock is extened to include weight.
class LegoBlockWeight extends LegoBlock {
  double weight; // weight of box

  // constructor for LegoBlockWeight
  LegoBlockWeight(double w, double h, double d, double m) {
    width = w;    //access parent variable
    height = h;   //access parent variable
    depth = d;    //access parent variable
    weight = m;    
  }    
}
  // Here, LegoBlock is extended to include color.
class ColorLegoBlock extends LegoBlock {
  int color; // color of box

  ColorLegoBlock(double w, double h, double d, int c) {
    width = w;   //access parent variable
    height = h;  //access parent variable 
    depth = d;   //access parent variable
    color = c;
  }    
}
public class Main {
  public static void main(String args[]) {
    LegoBlockWeight weightbox = new LegoBlockWeight(3, 5, 7, 8.37);
    LegoBlock plainbox = new LegoBlock();
    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 LegoBlockWeight reference to LegoBlock reference
    plainbox = weightbox;

    vol = plainbox.volume(); // OK, volume() defined in LegoBlock
    System.out.println("Volume of plainbox is " + vol);

  }
}



PreviousNext

Related