Java 101 — Constructor Methods

When we are writing a class, we can create a special method called a constructor method that runs once when an object is first instantiated. However constructor method are special.

They have to have the same name as the class name. It is the only method that you will ever Capitalize. We can pass arguments into a constructor.

It is the only method that you will ever Capitalize. We can pass arguments into a constructor.

public class Constructor
{
  private int month;
  private int day;
  public Constructor(int num1, int num2)
  {
  setMonth(num1);
  setDay(num2);
  }
  //Overloading Constructor
  public Constructor()
  {}
  //Setters
  public void setMonth(int inMonth)
  {
  if(inMonth > 12)
   {
   //error
   }else{
   month = inMonth;
   }
  }
  public void setDay(int inDay)
  {
  day = inDay;
  }
}

On our calling class we can pass something like this.

Constructor obj1 = new Constructor(10,28);

On the class Constructor we have are passing two numbers to the constructor class and setting those to integers to our setter methods to check for errors. As well we have an empty constructor in the bottom that simply allows the user to not pass any arguments and the program will still run.

Method Signature

Two of the components of a method declaration comprise the method signature — the method’s name and the parameter types.

Method Overloading

Refers to passing different amount and types of arguments to the same method.

In the following code example I am going to write one method with three different signatures.

public class OverloadingMethods
    {
      public int addNums(int num1, int num2)
      {
         int returnValue = num1 + num2;
         return returnValue;
      }
      public int addNums(int num1, int num2, int num3)
      {
         int returnValue = num1 + num2 + num3;
         return returnValue;
      }
      public int addNums (int num1, int num2, int num3, int num4)
      {
         int returnValue = num1 + num2+ num3+ num4;
         return returnValue;
      }
    }

Notice here how the methods share the same name but different method signature. This means we can either pass from two numbers to four numbers to our same method addNums and it would work.