23

What is the purpose of a constructor? I've been learning Java in school and it seems to me like a constructor is largely redundant in things we've done thus far. It remains to be seen if a purpose comes about, but so far it seems meaningless to me. For example, what is the difference between the following two snippets of code?

public class Program {    
    public constructor () {
        function();
    }        
    private void function () {
        //do stuff
    }    
    public static void main(String[] args) { 
        constructor a = new constructor(); 
    }
}

This is how we were taught do to things for assignments, but wouldn't the below do the same deal?

public class Program {    
    public static void main(String[] args) {
        function();
    }        
    private void function() {
        //do stuff
    }
}

The purpose of a constructor escapes me, but then again everything we've done thus far has been extremely rudimentary.

1
  • 11
    That is not a constructor. In fact, it doesn't even construct the class at all. A constructor would look like public Program(){\\..., and would be invoked new Program(). Commented Nov 13, 2013 at 0:54

12 Answers 12

50

Constructors are used to initialize the instances of your classes. You use a constructor to create new objects often with parameters specifying the initial state or other important information about the object

From the official Java tutorial:

A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type. 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.

Although Bicycle only has one constructor, it could have others, including a no-argument constructor:

public Bicycle() {
   gear = 1;
   cadence = 10;
   speed = 0;
}

Bicycle yourBike = new Bicycle(); invokes the no-argument constructor to create a new Bicycle object called yourBike.

8
  • 13
    Either you haven't understood him, or he doesn't understand what constructors are useful for either. Let's say your program is a card game: you would like 52 instances of a class named Card, each having a number and a color. A constructor is used to create an instance of the class Card. And you'll need to call it 52 times to have 52 cards: new Card(1, "hearts"), etc. Now each instance of Player (you also need a constructor for that), can have a List (constructed using a constructor) of cards. Read an introductory Java book, or the official Java tutorial.
    – JB Nizet
    Commented Nov 12, 2013 at 23:12
  • 3
    Cheers, this cleared up my confusion. It makes sense for setting default or initial parameters, but in everything we've done so far, this wasn't needed. I guess we were being prepped for when it is required to maintain consistency.
    – gator
    Commented Nov 12, 2013 at 23:26
  • 2
    Whoever downvoted me, care to explain why? From my answer, I'm definitely not harming the OP's knowledge of constructors in any way. :/
    – LotusUNSW
    Commented Nov 12, 2013 at 23:28
  • 2
    @LotusUNSW I have a feeling there's a downvoter-troll around here. Your answer's great. Commented Nov 13, 2013 at 0:21
  • 2
    @AJMansfield - Not true. You can put additional constructors in a superclass and still use a default constructor in a subclass, as long as the superclass includes an explicit, accessible constructor with no arguments and no throws clause. A class can contain more than one constructor. The choice of constructors to provide can be based on what sets of parameters can be used to initialize an instance. Sometimes those parameters must be specified in a constructor, because they're invariant in the instance. Commented Aug 19, 2015 at 16:17
33

A constructor is basically a method that you can use to ensure that objects of your class are born valid. This is the main motivation for a constructor.

Let's say you want your class has a single integer field that should be always larger than zero. How do you do that in a way that is reliable?

public class C {
     private int number;

     public C(int number) {
        setNumber(number);
     }

     public void setNumber(int number) {
        if (number < 1) {
            throws IllegalArgumentException("C cannot store anything smaller than 1");
        }
        this.number = number;
     }
}

In the code above, it may look like you are doing something redundant, but in fact you are ensuring that the number is always valid no matter what.

"initialize the instances of a class" is what a constructor does, but not the reason why we have constructors. The question is about the purpose of a constructor. You can also initialize instances of a class externally, using c.setNumber(10) in the example above. So a constructor is not the only way to initialize instances.

The constructor does that but in a way that is safe. In other words, a class alone solves the whole problem of ensuring their objects are always in valid states. Not using a constructor will leave such validation to the outside world, which is bad design.

Here is another example:

public class Interval {
    private long start;
    private long end;

    public Interval(long start, long end) {
        changeInterval(start, end);
    }

    public void changeInterval(long start, long end) {
        if (start >= end) {
            throw new IllegalArgumentException("Invalid interval.");
        }
        this.start = start;
        this.end = end;
    }
    public long duration() {
        return end - start;
    }
}

The Interval class represents a time interval. Time is stored using long. It does not make any sense to have an interval that ends before it starts. By using a constructor like the one above it is impossible to have an instance of Interval at any given moment anywhere in the system that stores an interval that does not make sense.

4
  • 1
    In general, Constructors (of non-final classes) should call only final or private methods. stackoverflow.com/questions/4893558/…
    – shiggity
    Commented Jun 1, 2015 at 18:40
  • 5
    +1 for the pragmatic answer. This answer satisfied not only the definition, but also my WHY inquire. "To be born valid" was the small piece of "usefulness" that i was missing to inteprid the necessity to use constructors. Commented May 5, 2016 at 17:43
  • I know this is extremely old, but is this a good way of thinking about "why". Lets say you make a contact list application. You hold addresses of 100 contacts, and a constructor to hold "valid" phone numbers. Every member is being initialised with a valid phone number?
    – someguy76
    Commented Feb 12, 2018 at 15:01
  • 1
    Correct. If you represent phone numbers as classes or a field of an address class, you may want to validate a phone number before you create an object that holds such information. Think of objects as things that will not be necessarily under your strict control after its creation. Your object may, for instance, end up being used by code that you did not write. So your objects should mean something. A constructor is a way to say that no object is allowed to exist in a way that violates its semantics.
    – Akira
    Commented Feb 14, 2018 at 0:25
10

As mentioned in LotusUNSW answer Constructors are used to initialize the instances of a class.

Example:

Say you have an Animal class something like

class Animal{
   private String name;
   private String type;
}

Lets see what happens when you try to create an instance of Animal class, say a Dog named Puppy. Now you have have to initialize name = Puppy and type = Dog. So, how can you do that. A way of doing it is having a constructor like

    Animal(String nameProvided, String typeProvided){
         this.name = nameProvided;
         this.type = typeProvided;
     }

Now when you create an object of class Animal, something like Animal dog = new Animal("Puppy", "Dog"); your constructor is called and initializes name and type to the values you provided i.e. Puppy and Dog respectively.

Now you might ask what if I didn't provide an argument to my constructor something like

Animal xyz = new Animal();

This is a default Constructor which initializes the object with default values i.e. in our Animal class name and type values corresponding to xyz object would be name = null and type = null

0
4

A constructor initializes an object when it is created . It has the same name as its class and is syntactically similar to a method , but constructor have no expicit return type.Typically , we use constructor to give initial value to the instance variables defined by the class , or to perform any other startup procedures required to make a fully formed object.

Here is an example of constructor:

class queen(){
   int beauty;

   queen(){ 
     beauty = 98;
   }
 }


class constructor demo{
    public static void main(String[] args){
       queen arth = new queen();
       queen y = new queen();

       System.out.println(arth.beauty+" "+y.beauty);

    }
} 

output is:

98 98

Here the construcor is :

queen(){
beauty =98;
}

Now the turn of parameterized constructor.

  class queen(){
   int beauty;

   queen(int x){ 
     beauty = x;
   }
 }


class constructor demo{
    public static void main(String[] args){
       queen arth = new queen(100);
       queen y = new queen(98);

       System.out.println(arth.beauty+" "+y.beauty);

    }
} 

output is:

100 98
3
  • Through a constructor (with parameters), you can 'ask' the user of that class for required dependencies.
  • It is used to initialize instance variables
  • and to pass up arguments to the constructor of a super class (super(...)), which basically does the same
  • It can initialize (final) instance variables with code, that may throw Exceptions, as opposed to instance initializer scopes
  • One should not blindly call methods from within the constructor, because initialization may not be finished/sufficient in the local or a derived class.
1
  • Instance initializer scopes can throw exceptions, as long as all the constructors are declared to throw the same exceptions.
    – user207421
    Commented Oct 15, 2015 at 2:43
2

A Java constructor has the same name as the name of the class to which it belongs.

Constructor’s syntax does not include a return type, since constructors never return a value.

Constructor is always called when object is created. example:- Default constructor

class Student3{  
    int id;  
    String name;  
    void display(){System.out.println(id+" "+name);}  
    public static void main(String args[]){  
        Student3 s1=new Student3();  
        Student3 s2=new Student3();  
        s1.display();  
        s2.display();  
    }  
} 

Output:

0 null
0 null

Explanation: In the above class,you are not creating any constructor so compiler provides you a default constructor.Here 0 and null values are provided by default constructor.

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor.

class Student4{  
    int id;  
    String name;  
    Student4(int i,String n){  
        id = i;  
        name = n;  
    }  
    void display(){System.out.println(id+" "+name);}  
    public static void main(String args[]){  
        Student4 s1 = new Student4(111,"Karan");  
        Student4 s2 = new Student4(222,"Aryan");  
        s1.display();  
        s2.display();  
    }  
}  

Output:

111 Karan
222 Aryan
1
  • 2
    There are some serious formatting issues in this post. Please edit to use code blocks. Commented Mar 22, 2015 at 13:04
1

It's used to set up the contents and state of your class. Whilst it's true you can make the simpler example with the main method you only have 1 main method per app so it does not remain a sensible approach.

Consider the main method to simply start your program and should know no more than how to do that. Also note that main() is static so cannot call functions that require a class instance and the state associated. The main method should call new Program().function() and the Program constructor should not call function() unless it is required for the setup of the class.

1

The class definition defines the API for your class. In other words, it is a blueprint that defines the contract that exists between the class and its clients--all the other code that uses this class. The contract indicates which methods are available, how to call them, and what to expect in return.

But the class definition is a spec. Until you have an actual object of this class, the contract is just "a piece of paper." This is where the constructor comes in.

A constructor is the means of creating an instance of your class by creating an object in memory and returning a reference to it. Something that should happen in the constructor is that the object is in a proper initial state for the subsequent operations on the object to make sense.

This object returned from the constructor will now honor the contract specified in the class definition, and you can use this object to do real work.

Think of it this way. If you ever look at the Porsche website, you will see what it can do--the horsepower, the torque, etc. But it isn't fun until you have an actual Porsche to drive.

Hope that helps.

1

Constructor is basicaly used for initialising the variables at the time of creation of object

1

I thought a constructor might work like a database in which only it defines variables and methods to control them

Then I saw objects that use variables and methods not defined in its constructor. So the discussion that makes the most sense to me is the one that tests variables values for validity, but the class can create variables and methods that are not defined in the constructor - less like a database and more like an over pressure valve on a steam locomotive. It doesn't control the wheels,etc.

Far less of a definition than I thought.

1
  • This doesn't answer the question
    – adao7000
    Commented Jul 27, 2016 at 22:15
1

Constructor will be helpful to prevent instances getting unreal values. For an example set a Person class with height , weight. There can't be a Person with 0m and 0kg

0

Let us consider we are storing the student details of 3 students. These 3 students are having different values for sno, sname and sage, but all 3 students belongs to same department CSE. So it is better to initialize "dept" variable inside a constructor so that this value can be taken by all the 3 student objects.

To understand clearly, see the below simple example:

class Student
{
    int sno,sage;
    String sname,dept;
    Student()
    {
        dept="CSE";
    }
    public static void main(String a[])
    {
        Student s1=new Student();
        s1.sno=101;
        s1.sage=33;
        s1.sname="John";

        Student s2=new Student();
        s2.sno=102;
        s2.sage=99;
        s2.sname="Peter";


        Student s3=new Student();
        s3.sno=102;
        s3.sage=99;
        s3.sname="Peter";
        System.out.println("The details of student1 are");
        System.out.println("The student no is:"+s1.sno);
        System.out.println("The student age is:"+s1.sage);
        System.out.println("The student name is:"+s1.sname);
        System.out.println("The student dept is:"+s1.dept);


        System.out.println("The details of student2 are");`enter code here`
        System.out.println("The student no is:"+s2.sno);
        System.out.println("The student age is:"+s2.sage);
        System.out.println("The student name is:"+s2.sname);
        System.out.println("The student dept is:"+s2.dept);

        System.out.println("The details of student2 are");
        System.out.println("The student no is:"+s3.sno);
        System.out.println("The student age is:"+s3.sage);
        System.out.println("The student name is:"+s3.sname);
        System.out.println("The student dept is:"+s3.dept);
    }
}

Output:

The details of student1 are
The student no is:101
The student age is:33
The student name is:John
The student dept is:CSE
The details of student2 are
The student no is:102
The student age is:99
The student name is:Peter
The student dept is:CSE
The details of student2 are
The student no is:102
The student age is:99
The student name is:Peter
The student dept is:CSE

1

Not the answer you're looking for? Browse other questions tagged or ask your own question.