You are on page 1of 28

CSE/IT 213 - Constructors

New Mexico Tech


September 14, 2011

Object Construction
If no defined constructors in your class, the default constructor for the parent class is used. A default constructor is one with no parameters.
Even when you dont extend a class explicitly, implicitly
all classes inherit the Object class, the mother-of-all
classes.
Object has a lone default constructor Object(), which
will set instances variables to their default:
booleans to false
numeric values to 0
objects to null.
1

Often the default is not what what you want.


public class Point {
private double x, y;
private String name;
public double getX() {
return x;
}
public double getY() {
return y;
}
public String getName() {
return name;
}

public static void main(String[] args) {


Point point = new Point();
System.out.println("Point " + point.getName());
System.out.println("(" + point.getX() + "," + point.getY() + "
}
}
$ java Point
Point null
(0.0,0.0)

However, considered bad programming to rely on default constructors.


Can lead to errors.
For example, changing the main to
public static void main(String[] args) {
Point point = new Point();
String s = point.getName();
s.charAt(1);
}
Throws a null pointer exception
Exception in thread "main" java.lang.NullPointerException
at Point.main(Point.java:26)
3

There is an important difference between fields (instance variables) and local variables.
You must always explicitly initialize local variables in a
method.
But if you dont initialize a field in a class, it is automatically initialized to a default (0, false, or null) depending
on its type.

This code throws an error


public class Point {
double x, y;
public double getX() {
int a;
return a*x;
}
....
}
$ javac Point.java
Point.java:9: variable a might not have been initialized
return a*x;
^
1 error
5

Once you write a constructor than there is no longer


a default constructor provided for you. You must write
your own. Its a good idea to have a default constructor.

Overloading
Often classes have multiple constructors. For example
the GregorianCalendar class had more than one constructor.
GregorianCalendar today = new GregorianCalendar();
or
GregorianCalendar ago = new GregorianCalendar(1968, 12,
1)
Note: The Calendar class declares a bunch of constants
for months and days of the week. Can use Calendar.MONDAY for Monday, Calendar.DECEMBER for
Decemeber.
7

This is called overloading.


Overloading occurs if several methods have the same
name but different parameters.
The compiler figures out which method to call by matching the parameter types in the headers of the various
methods with the types of the values used in the specific method call.
A compile-time error occurs if the compiler cannot match
the parameters or if more than one match is possible.
You can overload methods as well as constructors. Methods are described by their name and the parameters,
which is called their signature.

For example, the String class has multiple valueOf methods, each with a different signature
valueOf(boolean)
valueOf(char)
valueOf(char[])
valueOf(char[], int, int)
valueOf(double)
valueOf(float)
valueOf(int)
valueOf(long)
valueOf(Object)
The return type is not part of the signature. You cant
have two methods with identical signatures and different return types.

Make sure you initialize instance fields. Lots of ways to


do this.
Simplest
Initialize variables as you declare them. Instance variables are assigned before constructors are called.
public class Point {
private double x = 8.0;
private double y = 7.6;
...
}
Sets, initially, x to 8.0 and y to 7.6 every time an object
is created.
8

Initialization doesnt have to be a constant. Can call


methods.
class Point {
private static int nextId;
static int setId() {
int n = nextId;
nextId++;
return n;;
}
...
private int id = setId();
}

public class Point {


private static int nextId;
static int setId() {
int n = nextId;
nextId++;
return n;
}
private int id = setId();
public int getId() {
return id;
}
9

public static void main(String[] args) {


Point p0 = new Point();
Point p1 = new Point();
System.out.println("Point " + p0.getId());
System.out.println("Point " + p1.getId());
}
}
$ java Point
Point 0
Point 1

Parameter Names
Coming up with parameter names for constructor and
methods can be difficult/tedious. Single character parameters are not the best.
A couple of conventions
Use a as a prefix
double x, y;
public double setXY(double aX, double aY) {
x = aX;
y = aY;
}
10

Another way
Parameters variables shadow instance variables with
the same name. That is, for the scope of the method
the local variable hides the name of the instance variable.
double x, y;
public double setXY(double x, double y) {
this.x = x;
this.y = y;
}
this is the implicit parameter. this refers to the current
object.

Besides referring to the current object, if this is the


first line in a constructor, then it calls another constructor of the same class.
public class Point {
double x, y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public Point() {
//calls Point(double,
this(0.0, 0.0);

double)
11

}
}
public static void main(String[] args) {
Point p0 = new Point();
Point p1 = new Point(3, 5);
System.out.println("(" + p0.getX() + "," + p0.getY() + ")");
System.out.println("(" + p1.getX() + "," + p1.getY() + ")");
}
}
$ java Point
(0.0,0.0)
(3.0,5.0)

Another way to initialize instance variables, besides through


constructors or declarations, is to use an initialization
block. An initialization block is an arbitrary block of
code and executed when the constructor is called.
public class Point {
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public Point() {
}
12

{
x = 9.9;
y = 99.9;
}
public static void main(String[] args) {
Point p0 = new Point();
Point p1 = new Point(3, 5);
System.out.println("(" + p0.getX() + "," + p0.getY() + ")");
System.out.println("(" + p1.getX() + "," + p1.getY() + ")");
}
}
$ java Point
(9.9,99.9)
(3.0,5.0)

Can also do static initialization blocks for more complex


static initialization. Use the static to set off the block.

import java.util.*;
public class RandNum {
static int rand;
static
{
Random random = new Random();
rand = random.nextInt(100);
}
public int getRand() {
return rand;
}
13

public static void main(String[] args) {


RandNum rnum = new RandNum();
System.out.println(rnum.getRand());
}
}
$ java RandNum
23

With so many ways to initialize...


This is the order of things...
1. All data fields are initialized to their default value
(0, false, or null).
2. All field initializers and initialization blocks are executed, in the order in which they occur in the class
declaration.
3. If the first line of the constructor calls a second
constructor, then the body of the second constructor
is executed.
4. The body of the constructor is executed.

14

Destroying objects
When the reference count of an object reaches zero, it
is fair game for the garbage collector. But when the
garbage collector actually does this, who knows? If just
releasing memory, when the garbage collector releases
memory is mot that big of a deal. But when releasing something else, such as a file handle or network
connection need something else besides garbage collection. There is a finalize() method which is called
by the garbage collector to perform any last minute
clean-up. But as garbage collection may never occur,
such as on machines with plenty of memory, finalize
may never run. So cant guarantee it will work. Need
to call close or dispose or some other method.
15

Homework
import java.util.*;

public class Days {


public static void main(String[] args) {
GregorianCalendar today = new GregorianCalendar();
//days since moon landing
//months and days start with 0 (7/21/1969)
GregorianCalendar lunar = new GregorianCalendar(1969, 6, 20)
System.out.println(today.getTime().getTime());
System.out.println(birthday.getTime().getTime());

16

//method chaining
//today.getTime() is a method from Calendar class
// (today.getTime()) returns a Date class
// representing the time in ms since Epoch
//Epoch is 1/1/1970 00:00:00 GMT
//Date.getTime() returns a long of the ms
//since the epoch
// method chains read left to right
System.out.println((today.getTime().getTime()
- lunar.getTime().getTime()) / MS_IN_A_DAY);
}
public static final int MS_IN_A_DAY = 1000 * 60 * 60 * 24;
}
17

javap - java class file disassembler


The command javap java.lang.String will print out Javas
String method and constructor declarations.
public
public
public
public
public
public
public
public
public
public

static
static
static
static
static
static
static
static
static
native

java.lang.String
java.lang.String
java.lang.String
java.lang.String
java.lang.String
java.lang.String
java.lang.String
java.lang.String
java.lang.String
java.lang.String

valueOf(char[], int, int);


copyValueOf(char[], int, int)
copyValueOf(char[]);
valueOf(boolean);
valueOf(char);
valueOf(int);
valueOf(long);
valueOf(float);
valueOf(double);
intern();
18

You might also like