A Simple Class

Here is a class called Box that defines three member variables: width, height, and depth.

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

A class defines a new type of data. In this case, the new type is called Box.

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


Box myBox = new Box(); // create a Box object called mybox

myBox is an instance of Box.

mybox contains its own copy of each instance variable, width, height, and depth, defined by the class. To access these variables, you will use the dot (.) operator.

mybox.width = 100;

This statement assigns the width from mybox object to 100. Here is a complete program that uses the Box class:

 
class Box {
  int width;
  int height;
  int depth;
}
public class Main {
  public static void main(String args[]) {
    Box myBox = new Box();
    myBox.width = 10;

    System.out.println("myBox.width:"+myBox.width);
  }
}

The output:

myBox.width:10

Declaring Objects

Object creation is a two-step process.

  1. declare a variable of the class type.
  2. acquire a physical copy of the object and assign it to that variable using the new operator.

The new operator dynamically allocates memory for an object and returns a reference to it. The following lines are used to declare an object of type Box:


Box mybox; // declare reference to object 
mybox = new Box(); // allocate a Box object

The first line declares mybox as a reference to an object of type Box.

mybox is null now.
The next line allocates an actual object and assigns a reference to it to mybox. It can be rewritten to:

Box mybox = new Box();

Any attempt to use a null mybox will result in a compile-time error.


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

public class Main {
  public static void main(String args[]) {
    Box myBox;
    myBox.width = 10;
  }
}

If you try to compile the code above, you will get the following error message from the Java compiler.


D:\>javac Main.java
Main.java:10: variable myBox might not have been initialized
    myBox.width = 10;
    ^
1 error

Object instance

The following program declares two Box objects:

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

public class Main {
  public static void main(String args[]) {
    Box myBox1 = new Box();
    Box myBox2 = new Box();

    myBox1.width = 10;

    myBox2.width = 20;

    System.out.println("myBox1.width:" + myBox1.width);
    System.out.println("myBox2.width:" + myBox2.width);
  }
}

The output produced by this program is shown here:


myBox1.width:10
myBox2.width:20
Home 
  Java Book 
    Class  

Class Creation:
  1. Introducing Classes
  2. A Simple Class
  3. A Closer Look at new
  4. Variables and Initialization
  5. this Keyword
  6. A Demo Class
  7. The Person class: another demo
  8. Understanding static