© Mikael Olsson 2018
Mikael OlssonJava Quick Syntax Referencehttps://doi.org/10.1007/978-1-4842-3441-9_10

10. Class

Mikael Olsson1 
(1)
Hammarland, Länsi-Suomi, Finland
 

A class is a template used to create objects. Classes are made up of members, the main two of which are fields and methods. Fields are variables that hold the state of the object, whereas methods define what the object can do—the so-called behaviors of the object:

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

Object creation

To access a non-static class field or method from outside the defining class, an object of the class must first be created. That’s done using the new keyword, which will create a new object in the system’s memory:

public 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 from 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 beyond their package 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 area = r.getArea(); // 50 (5*10)
}  

Constructor

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

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

The constructor can have a parameter list, like any other method. As shown in the following code, 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 class MyApp
{ 
  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. The 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’re overshadowed by the parameters:

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

Constructor overloading

To support different parameter lists, the constructor can be overloaded. In the following example, if the class is instantiated without any parameters, the fields will be assigned the specified default values. With one parameter both fields will be set to the supplied value, and with two parameters 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

You can also use the this keyword to call one constructor from another. Known as constructor chaining, this 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 first constructor just shown, 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’s possible to create a class even if no constructors are defined. That’s because the compiler will then automatically create a default parameterless constructor:

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

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 (000), 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 because it makes the code easier to understand. For local variables the default values aren’t 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 mistakenly 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’re 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:

class MyApp
{ 
  public static void main(String[] args)
  { 
    MyApp a = new MyApp();
    // Make object available for garbage collection
    a = null;
  } 
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.185.196