jump to navigation

Java Constructors December 15, 2011

Posted by sodce in Java.
Tags:
add a comment

Java constructors instantiate an object. It creates an object out of the class you created. If you don’t provide a constructor then Java automatically creates a zero argument constructor. If you create a constructor then Java does not create a zero argument constructor. Constructors has the same name as the class and does not have a return type. So don’t put a “void” in as a return type. The compiler will fail to compile the statement.

There can be more than 1 Java constructor for a single class.  This is called method overloading.  When overloading a constructor, they are to have different parameters than the other constructors.  This is what allows the compiler know which constructor to run.  Constructors are usually public in scope.

public class BankAccount {
   private int acctNumber;
   private double balance;

   public BankAccount(int accountNumber, double beginBalance) {
       acctNumber = accountNumber;
       balance = beginBalance;
   }
}