-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?

8
  • you wouldn't be able to create objects/instances of classes, basically: you would only be able to use primitive datatypes. Commented Dec 19, 2017 at 8: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. Commented Dec 19, 2017 at 8: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. Commented Dec 19, 2017 at 8: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. Commented Dec 19, 2017 at 8:47
  • 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. Commented Dec 19, 2017 at 8:52

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.