KnowledgeBoat Logo
|

Computer Applications

How can class be used as user defined data types? Explain it with the help of an example.

Java Classes

12 Likes

Answer

Since a class is created by the user, it is also known as user defined data type. Take the example of the below class:

class Cuboid {
    private double height;
    private double width;
    private double depth;
    private double volume;

    public void input(int h, int w, int d) {
        height = h;
        width = w;
        depth = d;
    }

    public void computeVolume() {
        volume = height * width * depth;
        System.out.println("Volume = " + volume);
    }
}

After defining this class, I can use Cuboid as a new data type and create variables of Cuboid type as shown below:

public static void main(String[] args) {
    Cuboid c1 = new Cuboid();
    c1.input(5, 10, 5);
    c1.computeVolume();

    Cuboid c2 = new Cuboid();
    c2.input(2, 4, 9);
    c2.computeVolume();
}

This is how we can use class as a user defined data type.

Answered By

4 Likes


Related Questions