A Simple Class
Let’s begin or study of the class with a simple example. Here is a ‘class called Box that defines three instance variables: width, eight, and depth. Currently, Box docs not contain any methods (but some will be added soon).After this statement executes, my box will be an instance of Box. Thus, it will have I “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 variables, you will use the 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 my box the value 100, you would use the following statement:
This statement tells the compiler to assign the copy of width that is contained within
‘the my box 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: You should call the file that contains this program Box Demo java, because the main method is in the class called Box Demo, not the class called Box. When you compile this program, you will find that two .class files have been created, one for Box and lone for Box Demo. The Java·compiler automatically puts each class into its own .class file. is not necessary for both the Box and the Box Demo class to actually be in the same source file. You could put each class in its own file, called Box.java and Box Dcmo java, respectively.To run this program, you must execute Box Demo.class. When you do will seethe following output.
As-stated earlier, each object has its copies of the instance variables. This means that if you have two Box objects, each has its own copy of length, width, and height. It is important to understand that changes to the instance variables of one object have no effect on the variables of another. For example, the following program declares of Box objects: