0
3.7kviews
Create Rectangle and Cube class that encapsulates the properties of a rectangle and cube i.e. Rectangle has default and parameterized constructor and area() method.

Cube has default and parameterized constructor and volume method(). They share no ancestor other than Object. - Implement a class Size with size() method. This method accepts a single reference argument z. If z reference to a Cube, then size(z) return its volume. If z refers to an object of any other class, then size(z)- returns – 1. Use main() method in Size class to call size(..) method. -

Marks: 15 M

Year: Dec 2014

1 Answer
1
177views
class Rectangle {
    int length;
    int breadth;
    //Default constructor
    Rectangle() {
        length = 2;
        breadth = 2;
    }
    //Parameterized constructor
    Rectangle(int length, int breadth) {
        this.length = length;
        this.breadth = breadth;
    }
    //area method
    int area() {
        return length * breadth;
    }
}

class Cube {
    int side;
    //Default constructor
    Cube() {
        side = 2;
    }
    //Parameterized constructor
    Cube(int side) {
        this.side = side;
    }
    //volume method
    int volume() {
        return side*side*side;
    }
}

class Size {
    //size method which accepts reference object
    //It decides whether object is of Cube and returns volume else -1
    int calcSize(Object obj) {
        if(obj instanceof Cube) { //instanceof checks whether left is object of right
            return ((Cube)obj).volume(); //typecasting object to Cube object
        }
        else {
            return -1;
        }
    }

    public static void main(String args[]) {
        Cube cu = new Cube(2);
        Rectangle re = new Rectangle(2,3);
        Size si = new Size();
        int isCube = si.calcSize(cu);
        System.out.println(isCube);
        int isRect = si.calcSize(re);
        System.out.println(isRect);
    }
}
OUTPUT:
8
-1
Please log in to add an answer.