Skip to main content
OCA Java Programmer 1Z0-803

Java Create and overload constructors

By November 8, 2013No Comments

Welcome to TheUrbanPenguin and the series of free tutorials we have running to prepare you for the OCA exam 1ZO-803, the Java 7 SE Programmer 1 certification from Oracle. Each tutorial will step you through a specific objective of one of the 8 topics from the exam. In this tutorial we take a look at using constructors  within out Java class. Constructors as their name suggests help build instances of the class. As we instantiate, create an instance of a class, the constructor can be used to populate fields and call other methods as required. Constructors can be overloaded by which we mean that we can have more than one constructor defines for a single class and they we instantiate our object will determine which constructor is used.

Default Constructor

If we do not provide on constructor, and we have not set up any other inheritance, then the default no-args ( a constructor with no arguments) is inherited from the parent object which is the class Object.

This would be similar to defining the constructor within the class as

public class Class1 {
  public Class1(){

  }
}

When defining a new instance of this class, in our case Class1 we do not and cannot pass arguments to the object:

Class1 c1 = new Class1();

Note the parentheses do not hold any arguments.

Adding a single argument constructor

public class Class1 {
  String name;
  public Class1(String n){
    name = n; 
  }
}

As we have now defined the constructor with a single String argument that we identify as n, we can use the value of the argument to populate the name field in the class. We now have to pass a string as an argument when instantiating the object:

Class1 c1 = new Class1(“bob”);

We can see now the parentheses surround are string when creating the object.

Overloading Constructors

Overloading constructs is proving more than one constructor for a single class but with different options to allow for flexibility when creating object instances.

public class Class1 {
  String name;
  int age;
  public Class1(String n){
    name = n; 
  }
  public Class1(String n, int a){
  this(n);
  age = a; 
  }
}

As you now see we use two constructors for the one class. the first constructor accepts as before just the single String argument; the new constructor takes a String and an int. The save time in coding and maintenance it is often the case that the larger constructor will call the smaller constructor. In this case we see this with this(n). We pass the value of n from the second constructor through the the first constructor.

We now could create instances as:

Class1 c1 = new Class1("bob");

or

Class1 c1 = new Class1("bob",21);

Security

The access modifier for a constructor does not have to be public as we have used here. If we use private as the modifier then instance of the object could only be created from the same class, ie: in this case Class1.