Java Class and Object

A class is a template for an object, and an object is an instance of a class. Once a class is defined, this new type can be used to create objects of that type. The class is at the core of Java.

Class is the logical construct upon which the entire Java language is built because it defines the shape and nature of an object. As such, the class forms the basis for object-oriented programming in Java.

 Any concept you wish to implement in a Java program must be encapsulated within a class.

The general form of class defination is:

class classname { 
    type instance-variable1; 
    type instance-variable2; 
    // ... 
    type instance-variableN; 
    type methodname1(parameter-list) { 
        // body of method 
    type methodname2(parameter-list) { 
        // body of method 
    // ... 
     type methodnameN(parameter-list) { 
        // body of method 
  • The data, or variables, defined within a class are called instance variables. The code is contained within methods.
  • Collectively, the methods and variables defined within a class are called members of the class. In most classes, the instance variables are acted upon and accessed by the methods defined for that class.
  • Thus, as a general rule, it is the methods that determine how a class’ data can be used.


class Box {
    double width;
    double height;
    double depth;
    float volume;

    void calculateVolume() {
        volume = width * height * depth;

    void displayVolume() {
        System.out.println("The volume of object is : " + volume + "m^3");

Declaring Objects

new operator dynamically allocates memory for an object (allocates memory for object at runtime).

It has this general form:

class_var = new classname( );


Box mybox; // declare reference to object 
mybox = new Box(); // allocate a Box object
  • Here, the first line declares mybox as a reference to an object of type Box. After this line executes, mybox contains the value null, which indicates that it does not yet point to an actual object. Any attempt to use mybox at this point will result in a compile-time error.
  • The next line allocates an actual object and assigns a reference to it to mybox. After the second line executes, you can use mybox as if it were a Box object. But in reality, mybox simply holds the memory address of the actual Box object.

Both of these lines can be combined for convenience as

Box mybox = new Box();

So far, we've discussed that

  • A class creates a new data type that can be used to create objects. That is, a class creates a logical framework that defines the relationship between its members.
  • When you declare an object of a class, you are creating an instance of that class. Thus, a class is a logical construct. An object has physical reality.

Assigning Object Reference Variables

Let us look at scenario in which object reference variables is assgined to another variable. For example,

Box b1 = new Box();
Box b2 = b1;

When this fragment executes, b1 and b2 will both refer to the same object. The assignment of b1 to b2 did not allocate any memory or copy any part of the original object. It simply makes b2 refer to the same object as does b1.

Thus, any changes made to the object through b2 will affect the object to which b1 is referring, since they are the same object.

This can be depicted in memory diagram as:

ref-assignmentNote: Although b1 and b2 both refer to the same object, they are not linked in any other way. For example, a subsequent assignment to b1 will simply unhook b1 from the original object without affecting the object or affecting b2.

For example:

Box b1 = new Box(); 
Box b2 = b1; 
// ... 
b1 = null;

Here, b1 has been set to null, but b2 still points to the original object.


// example to illustrate class and object.
class Box {
    double width;
    double height;
    double depth; 
    // compute and return volume 
    double volume() {
        return width * height * depth;
    // sets dimensions of box
    void setDimensions(double w, double h, double d) {
        this.width = w;
        this.height = h;
        this.depth = d;

class DemoClassAndObject {
    public static void main(String args[]) {
        //creates two Box objects
        Box mybox1 = new Box();
        Box mybox2 = new Box();
        double volume; 
        // initialize each box 
        mybox1.setDimensions(10, 20, 15);
        mybox2.setDimensions(3, 6, 9); 
        volume = mybox1.volume();// get volume of first box 
        System.out.println("Volume of mybox1 is " + volume); 
        volume = mybox2.volume();// get volume of second box 
        System.out.println("Volume of mybox2 is " + volume);

The ouput of the program is:

Volume of mybox1 is 17500.0
Volume of mybox2 is 240.0


Access Control

How a member of class can be accessed is determined by the access specifier that modifies its declaration. Java supplies a rich set of access specifiers.

Here, let’s begin by examining access control as it applies to a single class. Java’s access specifiers are public, private, and protected. Java also defines a default access level. protected applies only when inheritance is involved.

When a member of a class is modified by the public specifier, then that member can be accessed by any other code.

When a member of a class is specified as private, then that member can only be accessed by other members of its class.

This is  why main( ) has always been preceded by the public specifier. main() is called by code that is outside the program—that is, by the Java run-time system.

 When no access specifier is used, then by default the member of a class is public within its own package, but cannot be accessed outside of its package. (A package is, essentially, a grouping of classes.)

An access specifier precedes the rest of a member’s type specification. That is, it must begin a member’s declaration statement. For example,

public int i; 
private double j; 
private int myMethod(int a, char b) { // ...

The following example helps to understand more about access specifier.

 * This program illustrates the difference between public,private and default specifier.
class Test {
    int a;              // default access 
    public int b;       // public access 
    private int c;      // private access 

    // methods to access c 
    void setC(int i) {
        c = i;          // set c's value 

    int getC() {        // get c's value 
        return c;

class AccessTest {
    public static void main(String args[]) {
        Test ob = new Test(); 
        // These are OK, a and b may be accessed directly 
        ob.a = 10;
        ob.b = 20; 
        // This is not OK and will cause an error 
        // ob.c = 100; // Error! 
        // You must access c through its methods 
        ob.setC(100); // OK 
        System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " + ob.getC());

The output of the program is:

a, b, and c: 10 20 100



Java Command-Line Arguments
Constructors and Garbage Collection