0

I referred this page for understanding about constructors in Java: http://www.javatpoint.com/constructor

So, I pretty much got it as in my own words:

constructor has no return value and is used to construct an object (fill with data) while creating it with the arguments supplied

What is the purpose of using constructor? Why can't the class just take care of this task by itself?

What I meant was use arguments in class definition directly instead of another definition for constructor that takes arguments inside a class.

EDIT 1: I was thinking something like this:

class Car(String theCountry) {
    String country;
    country = theCountry;
    String display() {
        return country;
    }
}

instead of this:

class Car {
    String country;
    Car(String theCountry) {
        country = theCountry;
    }
    String display() {
        return country;
    }
}

and the object initialization could still be the same: Car volvo = new Car("Sweden");

  • What do you mean by "class just take care of this task by itself"? Where do you propose the logic go? Perhaps a pseudo-code example of what you're envisioning would help us to better understand your question. – Dan Jul 6 '16 at 13:24
  • @Dan Hi Dan, I have added it in the question. – GP92 Jul 6 '16 at 14:52
  • You might be thinking about something like the @AllArgsConstructor in lombok? – SOFe Jul 6 '16 at 15:24
  • Constructors are methods and the class is unique. How would you have multiples constructors then? Yoy only have one class signature. – Tulains Córdova Aug 26 '16 at 14:52
8

Your example

class Car(String theCountry) {
    String country;
    country = theCountry;
    String display() {
        return country;
    }
}

has several flaws that "real" constructors dont.

You can only have one constructor. Constructor overloading has its very good uses and should be possible.

Every variable is part of the class. Suppose you need to create a temporary variable in your constructor like this:

class Country(String country) {
    String CountryCode;
    CountryCode = Locales.GetCode(country);
}

class Car(String theCountry) {
    String country;
    Country tmpCountry = Country(theCountry);
    country = tmpCountry.CountryCode;
    String display() {
        return country;
    }
}

Then your Car class suddenly has two fields: country and tmpCountry, which you probably don't want.

  • 1
    Hi thanks...i didn't know that we can have multiple constructors in a class. Now, it makes sense. But could it be the only reason? I do not understand your last sentence. How can tmpCountry a field of Car class and if it is, what's the problem? – GP92 Jul 6 '16 at 15:44
  • 2
    @JeevanPatnaik Curly braces are used to denote a scope. Not all scopes are equal. There are namespace scopes, class definition scopes, function scopes, loop scopes, conditional scopes, etc. I think you're confusing class { } with int MyFunc() { }. The former is a class definition scope, the latter is a method definition scope. They have very different purposes and you can't simply replace one with the other. I suggest you read up on Variable Scope and Definition vs. Declaration. – Dan Jul 6 '16 at 16:00
6

What is the purpose of using constructor? Why can't the class just take care of this task by itself? What I meant was use arguments in class definition directly instead of another definition for constructor that takes arguments inside a class.

If you are asking "is there a fundamental language design reason why this feature I want is impossible?" the answer is "no". Scala and F# have something like this, and the feature you desire was proposed for C# 6, though I believe it did not end up shipping. (Do a web search for "C# primary constructor" if you want the details.)

All features have to be thought of, designed, specified, implemented, tested, documented and shipped. If those things don't happen, you don't get the feature. For Java and C#, not all of those things happened, so, no such feature. It's a perfectly sensible feature, it's just going to take work to make it happen, and so far no one has done that work.

  • 2
    Yes, the feature was cut from C♯ 6, and has not yet re-appeared, although it will likely be part of records in some form. (I can't believe I'm explaining C♯ to Eric Lippert :-D) – Jörg W Mittag Jul 7 '16 at 22:34
  • 1
    @JörgWMittag: I've been a little out of the loop lately; my own fault of course. Trying to learn PHP, Hack, OCaml and Scala all at the same time has left little time for other hobbies. – Eric Lippert Jul 8 '16 at 14:52
  • Also, more recently, the Kotlin language now has a very similar feature. – Sean Burton Nov 28 '17 at 17:34
5

There are two ways of answering this question.

  1. If you're really asking "Why do I have to call new MyClass()? Why isn't MyClass() enough, like in Python?", this is largely a syntactical matter. For some reason or other the writers of the grammar for the Java language marked constructor invocations with a keyword. Other language authors have skipped the keyword. The reasons have to do more with all the other expression types that the language grammar contains than with the constructor invocation itself.

  2. But if you're asking "Why do I have to pass arguments at initialization time?", well, you don't have to. You can create a no-args constructor if you want. Constructors with arguments are in the language so that users can define their own classes which require mandatory bits of data which aren't known at class compile time, but only at object instantiation time.

  • What I meant was use arguments in class definition directly instead of another definition for constructor that takes arguments inside a class. – GP92 Jul 6 '16 at 12:18
  • 2
    Hmmm. What would you like to be able to write in Java? Can you give an example? – Kilian Foth Jul 6 '16 at 12:21
  • @KilianForth Hi Kilian, I have added it in the question – GP92 Jul 6 '16 at 14:53
  • @JeevanPatnaik How would you do an overload? – Pete Jul 6 '16 at 15:33
  • @KilianFoth Ok, I am pretty much new to Java. I haven't come across the overload concept yet. I have just this habit of theorizing everything before reading the whole thing :) – GP92 Jul 6 '16 at 15:35
2

you can overload a constructor, with fixed input in the class you would have to write a class for each. Like this you can get different instances. But you have to write a constructor for each one.

example:

MyClass instance = new MyClass(param1,param2);

MyClass instance2 = new MyClass(param1,param2,param3);
1

Well the purpose of constructor in java is to initialize the instance of a class. But not why we have constructors.

For example :

public class Car
{
   private int wheels;

   public Car(int wheels)
   {
      setNumber(wheels);
   }

   public void setNumber(int wheels)
   {
      this.wheels = wheels;
   }
}

As in the example above you can initialize instance of a class externally, using c.setWheels(4).

The reason why we are using constructor is because constructor does that, but in a way that is safe.

You can refer example below -

https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

http://www.flowerbrackets.com/learn-constructor-in-java/

http://www.flowerbrackets.com/java-constructor-example/

-2

The java language dictates that a constructur must be used to create an instance of a class. Any programming language has its syntax that every programmer should respect to make his program compile. Constructors are used in many languages other than java like C++, PHP, etc

  • this doesn't seem to offer anything substantial over points made and explained in prior 4 answers – gnat Aug 26 '16 at 10:55

protected by gnat Nov 27 '17 at 8:48

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

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