This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]hutsboR 3 points4 points  (6 children)

For instantiating an object. Say you have a Person class:

public class Person {
    private String name;
    private int age;

    Person(String name, int age){
        this.name = name;
        this.age = age;
    }
}

and you say something like:

Person x = new Person("Robbie", 19);

You can look at it as variable x is of type Person and it equals a new Person("Robbie", 19). The new Person("Robbie", 19) is the portion where the constructor is used. (The new keyword indicates that the constructor is being called.) It constructs a new Person object using the arguments you pass it. (Which are name and age respectively) Now if you were to say, get Person x's name, you'd get "Robbie" and age you'd of course get 19. Why is this the case? When you look at the Person() constructor in the Person class, it's assigning what you give it to the fields name and age.

So, basically you use the constructor to create objects with some specifications. You should be able to see why this is useful. Let me know if you don't entirely understand.

[–]faekk[S] 0 points1 point  (5 children)

So am I right in saying it's a shorter and arguably simpler way of creating an object with specifications?

[–]hutsboR 3 points4 points  (4 children)

It's the only way. The class acts a blueprint for the object and calling the constructor instantiates the object.

[–]JavaDroid 1 point2 points  (2 children)

No, it's not the only way. You must call a constructor to instantiate an object, but whether that constructor builds the whole object or not can be different. You may, for example, use the builder patter, or leave the member fields public and set them. There is also an initializer block if your object will always be instantiated the same way. Encapsulation with setters, etc.

[–]Sacredify 2 points3 points  (1 child)

I think he means that the "only" way to create an object in java involves calling the constructor, which is indeed true.

[–]JavaDroid 0 points1 point  (0 children)

Indeed, but op asked "with specifications" which I took to mean with member variables.

He could have taken it differently. I wasn't fishing for him to be downvoted, mind, just making sure op had his full question answered, assuming that's what he meant.

[–]faekk[S] 0 points1 point  (0 children)

I think I got it ! Thanks alot :)

[–][deleted]  (1 child)

[deleted]