Java. Constructors. Parameterized constructors. The keyword ‘this’. Garbage collection. The finalize() method




Constructors. Parameterized constructors. The keyword ‘this’. Garbage collection. The finalize() method


Contents


Search other websites:

1. What is called a class constructor? Constructor assignment

A constructor is a special method (function) of a class that is used to create a class object and initial initialization of the class’s internal variables. The constructor has the same name as the class. There can be several constructors in the class that differ in parameters among themselves. The constructor is called automatically when the class object is declared.

General form for the declaration of the constructor

ClassName(parameters)
{
    // body of constructor
    // ...
}

where

  • ClassName – The name of the constructor that matches the class name. The constructor does not return a value;
  • parameters – constructor parameters. The constructor can be without parameters (default).

2. Examples of using class constructors

Example 1. Declaring and using of the Month class containing information about the month of the year.

The class declares:

  • an internal, private variable of the class named month;
  • a parameterless constructor that sets the value of the internal variable ‘month’ to 1 (January);
  • constructor with one parameter that initializes the variable ‘month’;
  • access methods Get(), Set() to the internal variable month;
  • the Next() and Prev() methods that set the next and previous months in a year;
  • the MonthStr() method, which returns the name of the month.
public class Month 
{
    // class that describes the month of the year
    private int month; // internal variable (private keyword)

    // Declaring constructors of class
    // constructor without parameters
    Month()
    {
        month = 1; // month "January" by default
    }

    // constructor with one parameter
    Month(int mn)
    {
        if ((mn>=1)&&(mn<=12)) // check if the month number is set correctly 1..12
            month = mn;
        else
            month = 1;
    }

    // methods of class
    // access methods
    int Get() { return month; } // get the current number of the month

    void Set(int nmonth)
    {
        // set a new value
        if ((nmonth>=1)&&(nmonth<=12))
            month = nmonth;
    }

    // additional class methods
    // set the next month of the year
    int Next()
    {
        month++;
        if (month==13) month = 1;
        return month;
    }

    // set the previous month of the year
    int Prev()
    {
        month--;
        if (month==0) month = 12;
        return month;
    }

    // get the name of the month
    String MonthStr()
    {
        String s="";
        if (month==1) s = "Jan";
        if (month==2) s = "Feb";
        if (month==3) s = "Mar";
        if (month==4) s = "Apr";
        if (month==5) s = "May";
        if (month==6) s = "Jun";
        if (month==7) s = "Jul";
        if (month==8) s = "Aug";
        if (month==9) s = "Sep";
        if (month==10) s = "Oct";
        if (month==11) s = "Nov";
        if (month==12) s = "Dec";
        return s;
    }
}

Using a class in another function:

Month m1 = new Month(); // call the constructor without parameters
int d;
String s;

d = m1.Get(); // d = 1;
d = m1.Prev(); // d = 12
s = m1.MonthStr(); // s = "Dec"

Month m2 = new Month(5); // call the constructor with 1 parameter
d = m2.Get(); // d = 5
m2.Next();
s = m2.MonthStr(); // s = "Jun"
m2.Set(9);
s = m2.MonthStr(); // s = "Sep"

Example 2. Let the class MyRect, describing the rectangle, be given. The following internal variables are defined for a rectangle:

  • coordinates x, y of the upper-left corner of the screen;
  • the lengths of the sides dx, dy of the rectangle.

There are 3 constructors and 6 methods implemented in the class:

  • constructor without parameters;
  • constructor with 2 parameters (parameterized constructor);
  • constructor with 4 parameters (parameterized constructor);
  • methods for reading the values of internal variables GetX(), GetY(), GetDX(), GetDY();
  • method Set(), that sets a new values of internal variables;
  • method Square(), which calculates the area of the rectangle.
public class MyRect 
{
    // internal variables of class
    private int x, y, dx, dy; // private variables

    // Class constructors
    // constructor without parameters
    MyRect()
    {
        x = 0;
        y = 0;
        dx = 1;
        dy = 1;
    }

    // parameterized constructor with two parameters
    MyRect(int dx, int dy)
    {
        this.dx = dx;
        this.dy = dy;
        x = 0;
        y = 0;
    }

    // parameterized constructor with four oaraneters
    MyRect(int nx, int ny, int ndx, int ndy)
    {
        x = nx;
        y = ny;
        dx = ndx;
        dy = ndy;
    }

    // Class methods
    // reading the internal data of class
    int GetX() { return x; }
    int GetY() { return y; }
    int GetDX() { return dx; }
    int GetDY() { return dy; }

    // saving the new values to the internal data of the class
    void Set(int nx, int ny, int ndx, int ndy)
    {
        x = nx;
        y = ny;
        dx = ndx;
        dy = ndy;
    }

    // method that calculates the area of a rectangle
    int Square()
    {
        return (int)(dx*dy);
    }
}

In the parameterized constructor with 2 parameters, the internal parameters with the names dx, dy enter the input. Such names have internal class variables. To access internal class variables outside the body of the constructor, use the ‘this’ keyword:

...
this.dx = dx;
this.dy = dy;
...

Using a class in another code (for example, the main function):

// using of class
MyRect r1 = new MyRect(); // call the constructor without parameters
int d;

// checking
d = r1.GetDX(); // d = 1
r1.Set(5, 6, 2, 3); // call the Set() method of the class

int s = r1.Square(); // s = 6 - area of a rectangle

// call the constructor with two parameters
MyRect r2 = new MyRect(5,4);
d = r2.GetX(); // d = 0
d = r2.GetDY(); // d = 4

// call the constructor with four parameters
MyRect r3 = new MyRect(2,3,8,9);
d = r3.GetDY(); // d = 9
d = r3.Square(); // d = 72 - area, method Square()

3. What are parameterized constructors?

Parameterized constructors are constructors that receive parameters.






4. Why the ‘this’ keyword used? Example

The ‘this’ keyword is used to get a reference to the object in the method that called it. The ‘this’ keyword can be used in the body of any method to refer to the current object.

Example. Let the class DWeek describing the (realizing) day of the week be given.

The class declares:

  • internal variable day;
  • constructor without parameters;
  • constructor with one parameter;
  • access methods Get() and Set();
  • the IsDayOff() method, which determines whether the day is day off or not.
// Class that realises the day of the week
public class DWeek 
{
    // internal private variable day
    private int day;

    // Class constructors
    DWeek() // constructor without parameters
    {
        day = 1; // Monday
    }

    // constructor with 1 parameter
    DWeek(int day)
    {
        // access to the instance variable of class using the keyword 'this'
        if ((day>=1)&&(day<=7))
        this.day = day;
    }

    // access methods
    int Get() { return day; }

    void Set(int day)
    {
        // access to the instance variable: this.day
        if ((day>=1)&&(day<=7))
        this.day = day;
    }

    // A method that determines whether the day is day off or not
    boolean IsDayOff()
    {
        int d; // internal variable

        // call the Get() method of the class using the 'this' keyword
        d = this.Get(); // take the current day

        boolean b = true;
        if ((d>=1)&&(d<=5)) b = false;
        return b;
    }
}

In a constructor with 1 parameter, the input parameter has the same name as the internal variable of class ‘day’. Therefore, to access the instance variable of class ‘day’, the keyword ‘this’ is used:

// constructor with one parameter
DWeek(int day)
{
    // access to the instance variable of class 'day' using the 'this' keyword
    this.day = day;
}

The same applies to the Set() method, in which the name of the input parameter is the same as the instance name of the class. In these two cases, the use of the ‘this’ keyword is effective. Of course, if you want, you can change the name of the input parameter and dispense with the word ‘this’.

In the IsDayOff() method, the ‘this’ keyword (for demonstration purposes) is used to access the Get() method.

Using a class in another method

public static void main(String[] args) 
{
    // using the DWeek class
    DWeek dw1 = new DWeek(); // calling the constructor without parameters
    boolean b;
    int d;

    b = dw1.IsDayOff(); // b = false
    d = dw1.Get(); // d = 1

    DWeek dw2 = new DWeek(7);
    b = dw2.IsDayOff(); // b = true
    dw2.Set(4);
    d = dw2.Get(); // d = 4
    b = dw2.IsDayOff(); // b = false

    System.out.println(d);
}

5. What does the term “garbage collection” mean? How does “garbage collection” occur?

“Garbage collection” is an automatic destruction of objects in RAM that are no longer used in the program. “Garbage collection” is used to free memory for objects that still exist in the program and are no longer used. In the Java language, you do not need to explicitly destroy objects. Different implementations of Java use different approaches to “garbage collection.”



6. What is the purpose of the finalize() method in Java?

The finalize() method specifies the actions that must be performed before the object is destroyed. This can be, for example, saving intermediate data/results, destroying a file descriptor, etc.

If the finalize() method is defined in the class, it is called before the class object must be destroyed by the “garbage collector”. This procedure looks like this:

  • “garbage collector” from time to time starts and checks for the presence of objects that are not referenced. These objects need to be deleted;
  • for found objects, the finalize() method is first called if it is defined in the class. In this method, appropriate actions are taken to release “non-Java” resources;
  • the found object is deleted.

The finalize() method has the following general form:

protected void finalize()
{
    // body of method
    // ...
}

This method must be declared in the class, for example:

class MyClass
{
    // ...

    protected void finalize()
    {
        // ...        
    }

    // ...
}

 

7. How is it possible to assign variable the references to class objects?

If two variables are declared (two objects) of a certain class with the names v1 and v2 and the memory is allocated for the variable v1 using the ‘new’ operator, then the string

v2 = v1;

will mean the following:

  • the variable v2 contains a reference to the object v1;
  • the variables v2 and v1 refer to the same memory area. This means that the memory for the variable v2 is not allocated. Changes to the reference in the variable v1 will lead to the same changes in the variable v2 (and vice versa);
  • these variables are not related. That is, if you change the value of one of the variables, it will not affect the value of the other variable (the other variable will remain referenced to the original object).


Related topics