Programming Tutorials

A simple Box class in Java

By: aathishankaran in Java Tutorials on 2007-02-20  

Here is a class called Box that defines three instance variables: width, height, and depth. Currently, Box does not contain any methods (but some will be added soon).

class Box {
   double width;
   double height;
   double depth;
}

As stated, a class defines a new type of data. In this case, the new data type is called Box. You will use this name to declare objects of type Box. It is important to remember that a class declaration only creates a template; it does not create an actual object. Thus, the preceding code does not cause any objects of type Box to come into existence.

To actually create a Box object, you will use a statement like the following:

Box mybox = new Box() ;

After this statement executes, mybox will be an instance of Box. Thus, it will have "physical"reality. For the moment, don't worry about the details of this statement.

Again, each time you create an instance of a class, you are creating an object that contains its own copy of each instance variable defined by the class. Thus, every Box object will contain its own copies of the instance variables width, height, and depth. To access these object you will use the dot (.) operator. The dot operator links the name of the object with the name of an instance variable. For example, to assign the width variable of mybox the value 100, you would use the following statement:

mybox.width = 100;

This statement tells the compiler to assign the copy of width that is contained within the mybox object the value of 100. in general, you use the dot operator to access both the instance variables and the methods within an object.

Here is a complete program that uses the Box class:

class Box {
double width;
double height;
double depth;
}

class Box {
   double width;
   double height;
   double depth;
}

class BoxDemo {
    public static void main(String args[]) {
        Box mybox = new Box();
        double vol;
        mybox.width = 10;
        mybox.height = 20;
        mybox.depth = 15;
        vol = mybox.width * mybox.height * mybox.depth;
        System.out.println("volume is" + vol);
    }
}





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)