Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of a constructor in Java?

Tags:

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.

like image 955
gator Avatar asked Nov 12 '13 23:11

gator


People also ask

What is the main purpose of a constructor?

The purpose of constructor is to initialize the object of a class while the purpose of a method is to perform a task by executing java code. Constructors cannot be abstract, final, static and synchronised while methods can be. Constructors do not have return types while methods do.

What is the use of constructor in Java with example?

Example 1: Java Constructor Main obj = new Main(); Here, when the object is created, the Main() constructor is called. And, the value of the name variable is initialized. Hence, the program prints the value of the name variables as Programiz .


2 Answers

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.

like image 178
LotusUNSW Avatar answered Oct 13 '22 23:10

LotusUNSW


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.

like image 45
Akira Avatar answered Oct 13 '22 22:10

Akira