Tushar Monirul
Tushar Monirul

Reputation: 5064

what is the extra benefit of creating constructor in java?

I have noticed a thing that a constructor and a simple method of a class do the same work. what is the exact reason to create a construct of a class? If i create MyClass(){} constructor and MyClassMethod(){} method it will do the same work as I write the body part of those method and constructor. So what is the need of construct? Does it have any special use ?

Upvotes: 7

Views: 18712

Answers (9)

Isuru
Isuru

Reputation: 41

These are the benefits of constructors.

  • Automatic initialization of objects at the time of their declaration.
  • Multiple ways to initialize objects according to the number of arguments passes while declaration.
  • The objects of child class can be initialised by the constructors of base class.

Upvotes: 0

rashedcs
rashedcs

Reputation: 3725

A constructor is a special method of a class or structure in object-oriented programming that initializes an object of that type.

Some points :

1. A constructor eliminates placing the default values.
2. A constructor eliminates calling the normal method implicitly.

Upvotes: 1

AllTooSir
AllTooSir

Reputation: 49372

Some points :

1) Constructors are the only way to set final instance variables .

public class SomeType {
   final int x ;
   SomeType(int y){
     x=y;
   }
}

2) A class with private constructor cannot be sub classed.

3) If your class is a subclass and the base class doesn't have a default constructor , then you need a constructor in your class to call the super class constructor.

Upvotes: 5

c.s.
c.s.

Reputation: 4816

A constructor and a method are two different things. The fact that you can write the same or similar code inside them is irrelevant.

When a new object is created a constructor is called. If you don't specify one the compiler will create a default one for you. This is the place where initializaton of the object's fields takes place and memory is allocated for the object. This is a concept that all object-oriented languages have. A new object must be initialized somehow. Memory needs to be allocated. In Java you don't manage the memory yourself (at least not directly anyway) so this is the purpose of the constructor. Note that since a constructor is always executed, this behaviour is enforced as soon as you call e.g. Person p = new Person();.

Now since a constructor is always being called, you have an option here: do you let the default constructor execute or do you create one yourself? Perhaps there are fields that need to be initialized in a way other than their default values. Or perhaps you need to not allow creating an object without providing some values. If you define a constructor yourself, the compiler does not create a default one for you. So if I have public Person(String firstName, String lastName) {} then I have created a specific rule that is again enforced by the system: a new object of class Person cannot be created unless you give a first name and last name:

Person p = new Person(); // this would give a compile error
Person p = new Person("John", "Smith"); // this is the only way to create an object now

Using a method you cannot enforce this. The programmer using your class might call your method or not. The constructor is a part of the lifecycle of the object. Methods define the behaviour of the object

Upvotes: 6

robjohncox
robjohncox

Reputation: 3665

Essentially a constructor is just a special method that implicitly returns an object of its containing type. You should generally use constructors for creating objects - this is what people expect to see.

However, there is a useful idiom called the factory method (more info at this link) which is essentially using a static method to construct an object, the key advantages being

  • You can give a factory method a more descriptive name (whereas of course a standard constructor has to be named after the containing class).
  • They don't have to return an object, giving more flexibility.
  • They can return a sub-types of the class.

Upvotes: 3

Zain Zafar
Zain Zafar

Reputation: 1607

Constructor is not like simple methods. It is called every time when the object of that particular class is created. You don't need to call it explicitly.


There are somethings that we need to do immediately when the object is created, for instance when you create a GUI kind of thing you want to set many properties on the time of creation like size of window etc. Another benefit of constructor is security of class. You cannot create a object unless you know the right perimeters of constructor.


More details:http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

Upvotes: 1

Benjamin Schwalb
Benjamin Schwalb

Reputation: 1134

If you create a new Object of MyClass it will automatically call the constructor - you can initialize all members within it, and be sure that this object´s members are all initialized.

Generally:
A constructor is always called once when you create a new Object of this class, and you can´t call it manually.
And don´t do "real" work in a constructor, as it will slow down the creation of objects of this class - only initialize your class/members there.

You can also use different constructors, depending on your needs - but if you create a constructor, there is no more default constructor!

Example:

public MyClass {

   int score;

   public MyClass(int sc) { // already know the score
    score = sc;
   }

   public MyClass() { // don´t know the score yet
    score = 1;
   }

   public void addScore() {
   score += 5;   // i know for sure that score is not zero 
   }

}

Upvotes: 4

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

One of the benefits of using a constructor over a method is that you can be assured the constructor was called and the work within the constructor was performed.

The language specifies that to construct an object a constructor must be called. So if you use a custom method to establish the initial state of your object, you will need to call the default constructor first. Why make two method calls when you can perform the work in one call the constructor and be assured the object has been properly initialized?

public class Test(){

    private Integer x;

    public Test(){

    }

    public Test(Integer x){
       this.x = x;
    }

    public void setX(Integer x){
       this.x = x;
    }

    public void doSomethingWithX(){
       this.x.toString();
    }
}

Test test = new Test(8);
test.doSomethingWithX(); //I know x has been declared and assigned

Test test = new Test();
test.doSomethingWithX(); //X has not been assigned results in NPE

Upvotes: 4

Beryllium
Beryllium

Reputation: 12988

You can set final fields without initializer in a constructor. This helps to build immutable instances:

class Number extends Expr {
    private final int n;

    public Number(int n) {
        this.n = n;
    }

    public int getValue() {
        return this.n;
    }
}

So after a constructor like this, you can rely on the fact that the instance is initialized completely (and in this case, it's values are immutable/constant).

Upvotes: 1

Related Questions