-1

I was confused by constructor for many days , reading many code and books ,but still did not fully understand what constructor actually is. Could any one show what would happen without constructor in Java?

zaerymoghaddam
  • 3,037
  • 1
  • 27
  • 33
user9060262
  • 11
  • 1
  • 1
  • you wouldn't be able to create objects/instances of classes, basically: you would only be able to use primitive datatypes. – Stultuske Dec 19 '17 at 08:42
  • 2
    Even you don't write any constructor, a default constructor exists there. So you can still create objects without passing any parameters. But if you want to create an object by passing parameters, you must define a constructor. – Nabin Bhandari Dec 19 '17 at 08:45
  • By the way, all classes inherit from the `Object` class, so if you don't write a constructor on your class, you still have the one from the `Object` class. So ALL classes have a constructor. – Bentaye Dec 19 '17 at 08:45
  • @NabinBhandari the question is not: "what if I don't put a constructor", it is "what if there weren't constructors in Java". Explaining the default constructor is nice, but not really relevant here. – Stultuske Dec 19 '17 at 08:47
  • @Stultuske chill out man, that was just a comment, not an answer. – Nabin Bhandari Dec 19 '17 at 08:48
  • @NabinBhandari true, but still, the comment is not about what is asked. No harm in mentioning that, is there? – Stultuske Dec 19 '17 at 08:50
  • 1
    Please understand that SO is not a replacement for you doing that *learning* part. There are zillions of books out there explaining what constructors are, how to use them, what happens if you dont provide one in your class. – GhostCat Dec 19 '17 at 08:52
  • If constructors weren’t a thing, there would be another way to instantiate a class. – achAmháin Dec 19 '17 at 09:25

1 Answers1

3

All classes have a constructor. If you don't specify one, you will get a default constructor with no parameters.

So when you do this:

class Test {

}

You will actually get this:

class Test {
  Test() {
    super(); // This is a call to the constructor of the Object class.
  }
}

The constructor lets you create instances of the class with the new keyword. Like this:

Test test = new Test(); // This calls the default constructor.

If there weren't constructors in Java, you wouldn't be able to create objects.

marstran
  • 26,413
  • 5
  • 61
  • 67