I am struggling to fully understand the usage of constructors in Java.
What I have learned so far about constructors is the following:
- same name as class
- abbreviation ctor
- overloading
- no return type
- create an object of a class
- every class has a default constructor
When for example a string has to be returned from a class that needs to be called then a method could be created, i.e. a constructor will not be sufficient as this will not return anything.
Attempt to answer the question
In order to explain what I mean, I have created a class with two constructors and two methods that return a string.
public class HelloWorldConstructor {
public HelloWorldConstructor() { }
public HelloWorldConstructor(String a) {
saySomething(a);
}
public HelloWorldConstructor(String a, String b) {
saySomething(a, b);
}
void saySomething(String a) {
System.out.println(a);
}
void saySomething(String a, String b) {
System.out.println(a + ", " + b);
}
}
Option 1
It is possible to return a string by calling the method that resides in the class.
public class CallConstructor {
public static void main(String[] args) {
HelloWorldConstructor hwc = new HelloWorldConstructor();
hwc.saySomething("allo");
hwc.saySomething("allo", "allo");
}
}
returns:
allo
allo, allo
Option 2
It is also possible to return a string by calling the constructor directly.
public class CallConstructor2 {
public static void main(String[] args) {
new HelloWorldConstructor("allo");
new HelloWorldConstructor("allo", "allo");
}
}
returns the same as option 1.
Discussion
When option 2 is chosen, then two objects have to be created instead of one as depicted by option 1, but when to choose option 2 and when option 1? In this case I think it is better to choose option 1 as one object will be created, but option 2 could be suitable when other circumstances are applicable.
The constructor in the example just gives an initial value to class members.
https://stackoverflow.com/a/19941847/2777965
Constructors are used to initialize the instances of your classes. You use a constructor to create new objects often with parameters specifying the initial state or other important information about the object
After reading about theory and Q&As about constructors I am struggling to fully understand them. I know how to call a constructor and how to call a method, but I cannot rationalize this.
- A constructor has to be called directly when ...
- Constructor overloading will be done when ...
- Methods will be called directly by calling the default constructor when ...