Provide Best Programming Tutorials

Constructor In Java

Providing Constructors for Your Classes

First let’s define Bicycle class:

public class Bicycle {
   private int gear;
   private int cadence;
   private int speed;
}

Define a constructor with argument

For example, Bicycle has one constructor:

public Bicycle(int startCadence, int startSpeed, int startGear) {
    gear = startGear;
    cadence = startCadence;
    speed = startSpeed;
}

To create a new Bicycle object called myBike, a constructor is called by the new operator:

Bicycle myBike = new Bicycle(30, 0, 8);

new Bicycle(30, 0, 8) creates space in memory for the object and initializes its fields.

You can define as much as constructors as you wish.For example we define another constructor:

public Bicycle(int startCadence, int startSpeed) {
    cadence = startCadence;
    speed = startSpeed;
}

Unlike the previous one,this constructor revice two arguments.

Default constructor

A default constructor is a constructor with no parameters.

Java Constructor in hierarchy

class A {/*from  w  w w. j a v  a2 s.  com*/
  A() {
    System.out.println("Inside A's constructor.");
  }
}

// Create a subclass by extending class A.
class B extends A {
  B() {
    System.out.println("Inside B's constructor.");
  }
}

// Create another subclass by extending B.
class C extends B {
  C() {
    System.out.println("Inside C's constructor.");
  }
}

public class Main{
  public static void main(String args[]) {
    C c = new C();
  }
}

output:

Inside A's constructor.
Inside B's constructor.
Inside C's constructor.

Java Constructors Overload

Method overloading is to declare two or more methods with the name but different type or count of parameters.

In addition to overloading normal methods, you can also overload constructor methods.

package oop.constructor;

public class Bycicle {
    private int gear;
    private int cadence;
    private int speed;

    public Bycicle() {
    }

    public Bycicle(int gear) {
        this.gear = gear;
    }

    public Bycicle(int gear, int cadence) {
        this.gear = gear;
        this.cadence = cadence;
    }

    public Bycicle(int gear, int cadence, int speed) {
        this.gear = gear;
        this.cadence = cadence;
        this.speed = speed;
    }

}
package oop.constructor;

public class OopClient {


    public static void main(String[] args) {
        Bycicle bycicle = new Bycicle();
        Bycicle bycicle1 = new Bycicle(1);
        Bycicle bycicle2 = new Bycicle(1, 2);
        Bycicle bycicle3 = new Bycicle(1, 2, 3);
    }

}

Leave a Reply

Close Menu