Superclass variable can reference a subclass variable in java

A reference variable of a superclass can be assigned a reference to any subclass derived from that superclass. You will find this aspect of inheritance quite useful in a variety of situations.

For example, consider the following:

/* JAVA program to understand superclass variable can reference a subclass variable */
/* */

class Box
    void volume()
        return 100;
class BoxWeight extends Box
    int height;
    int depth;
    int length;
    double breadth;
    BoxWeight(int a,int b, int c , double d)
    double volume()
        return height*length*height;
    int weight()
        return length*breadth*depth;

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);
        // 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);

Here, weightbox is a reference to BoxWeight objects, and plainbox is a reference to Box objects. Since BoxWeight is a subclass of Box, it is permissible to assign plainbox a reference to the weightbox object.

Latest Posts


Leave a Comment

Your email address will not be published. Required fields are marked *