News & UpdatesProgrammingWeb programming StoreMy Projects
Links
Affiliates

Java Tutorial – 11 – Class

A class is a template used to create objects. They are made up of members, the main two of which are fields and methods. Fields are variables that hold the state of the object, while methods define what the object can do.

class MyRectangle         
{
  int x, y;
  int getArea() { return x * y; } 
}

Object creation

To access a class’s fields and methods from outside the defining class, an object of the class must first be created. This is done by using the new keyword, which will create a new object in the system’s memory.

class MyApp
{
  public static void main(String[] args) 
 {
    // Create an object of MyRectangle
    MyRectangle r = new MyRectangle();
  }
}

An object is also called an instance. The object will contain its own set of fields, which can hold values that are different to those of other instances of the class.

Accessing object members

In addition to creating the object, the members of the class that are to be accessible need to be declared as public in the class definition.

class MyRectangle         
{
  public int x, y;
  public int getArea() { return x * y; } 
}

The members of this object can now be reached by using the dot operator after the instance name.

public static void main(String[] args)
{
  MyRectangle r = new MyRectangle();
  r.x = 10;
  r.y = 5;
  int z = r.getArea(); // 50 (5*10)
}

Constructor

The class can have a constructor. This is a special kind of method used to instantiate (construct) the object. It always has the same name as the class and does not have a return type, since it implicitly returns a new instance of the class. To be accessible from another class it needs to be declared with the public access modifier. When a new instance of the MyRectangle class is created, by using the new syntax, the constructor method is called, which in the example below sets the fields to some default values.

class MyRectangle         
{
  int x, y;
  public MyRectangle() { x = 10; y = 20; }
 
  public static void main(String[] args)
  {
    MyRectangle r = new MyRectangle();
  }
}

The constructor can have a parameter list, just as any other method. As seen below, this can be used to make the fields’ initial values depend on the parameters passed when the object is created.

class MyRectangle         
{
  int x, y;
  public MyRectangle(int a, int b) { x = a; y = b; }
 
  public static void main(String[] args)
  {
    MyRectangle r = new MyRectangle(20,15);
  }
}

This keyword

Inside the constructor, as well as in other methods belonging to the object, a special keyword called this can be used. This keyword is a reference to the current instance of the class. If, for example, the constructor’s parameters have the same names as the corresponding fields, then the fields could still be accessed by using the this keyword, even though they are overshadowed by the parameters.

class MyRectangle         
{
  int x, y;
  public MyRectangle(int x, int y) 
  { 
    this.x = x; this.y = y;
  }
}

Constructor overloading

The constructor can be overloaded to support different parameter lists. In the example below, if the class is instantiated without any parameters the fields will be assigned default values. With one argument both fields will be set to that value, and with two arguments each field will be assigned a separate value. Attempting to create an object with the wrong number of arguments or with incorrect data types will result in a compile-time error, just as with any other method.

class MyRectangle         
{
  int x, y;
  public MyRectangle()             { x = 10; y = 20; }
  public MyRectangle(int a)        { x = a;  y = a;  }
  public MyRectangle(int a, int b) { x = a;  y = b;  }
}

Constructor chaining

The this keyword can also be used to call one constructor from another. This is known as constructor chaining, and allows for greater code reuse. Note that the keyword appears as a method call, and that it must be on the first line in the constructor.

public MyRectangle()             { this(10,20);  }
public MyRectangle(int a)        { this(a,a);    }
public MyRectangle(int a, int b) { x = a; y = b; }

Initial field values

If there are fields in the class that need to be assigned default values, such as in the case of the first constructor above, the fields can simply be assigned at the same time as they are declared. These initial values will be assigned before the constructor is called.

class MyRectangle         
{
  int x = 10, y = 20;
}

Default constructor

It is possible to create a class even if no constructors are defined. This is because the compiler will then automatically create a default parameterless constructor.

class MyClass
{
  public static void main(String[] args)
  {
    // Default constructor used
    MyClass c = new MyClass();
  }
}

Null

The built-in constant null is used to represent an uninitialized object. It can only be assigned to objects and not to variables of primitive types. The equal to operator (==) can be used to test whether an object is null.

String s = null;
if (s == null) s = new String();

Default values

The default value of an object is null. For primitive data types the default values are as follows: numerical types become 0, a char has the Unicode character for zero (\0000) and a boolean is false. Default values will be automatically assigned by the compiler, but only for fields and not for local variables. However, explicitly specifying the default value for fields is considered good programming since it makes the code easier to understand. For local variables the default values will not be set by the compiler. Instead, the compiler forces the programmer to assign values to any local variables that are used, so as to avoid problems associated with using unassigned variables.

class MyApp
{
  int x; // field is assigned default value 0
 
  int dummy() 
  {
    int x; // local variable must be assigned if used
  }
}

Garbage collector

The Java runtime environment has a garbage collector that periodically releases the memory used by objects when they are no longer needed. This frees the programmer from the often tedious and error-prone task of memory management. An object will be eligible for destruction when there are no more references to it. This occurs, for example, when the object goes out of scope. An object can also be explicitly dropped by setting its references to null.

Recommended additional reading:
Sams - Teach Yourself Java in 24 Hours