Calling a constructor with the command new
causes several things to happen.
First, space is reserved in the computer memory for storing object variables.
Then default or initial values are set to object variables (e.g. an int
type variable receives an initial value of 0).
Lastly, the source code in the constructor is executed.
Person joan = new Person("Joan Ball");
Person ball = joan;
An object's internal state is not copied when a variable's value is assigned. A new object is not being created in the statement Person ball = joan;
— the value of the variable ball is assigned to be the copy of joan's value, i.e. a reference to an object.
null
value of a reference variableThe null
reference can be set as the value of any reference type variable.
In the Java programming language the programmer need not worry about the program's memory use. From time to time, the automatic garbage collector of the Java language cleans up the objects that have become garbage.
Printing a null
reference prints "null".
Assisted creation of constructors, getters, and setters
Go inside the code block of the class, but outside of all the methods, and simultaneously press ctrl and space. If your class has e.g. an object variable balance
, NetBeans offers the option to generate the getter and setter methods for the object variable, and a constuctor that assigns an initial value for that variable.
If you want to handle dates in your own programs, it's worth reading about the premade Java class LocalDate. It contains a significant amount of functionality that can be used to handle dates.
The idea behind abstraction is to conceptualize the programming code so that each concept has its own clear responsibilities.
public boolean before(SimpleDate compared) {
// first compare years
if (this.year < compared.year) {
return true;
}
if (this.year > compared.year) {
return false;
}
// years are same, compare months
if (this.month < compared.month) {
return true;
}
if (this.month > compared.month) {
return false;
}
// years and months are same, compare days
if (this.day < compared.day) {
return true;
}
return false;
}
Even though the object variables year
, month
, and day
are encapsulated (private
) object variables, we can read their values by writing compared.*variableName*
. This is because a private
variable can be accessed from all the methods contained by that class.
Using two equality signs compares the equality of the values stored in the "boxes of the variables" — with reference variables, such comparisons would examine the equality of the memory references.
The method equals
is similar to the method toString
in the respect that it is available for use even if it has not been defined in the class. The default implementation of this method compares the equality of the references.