+ 1

Is a constructor in class any sort of variable before an instance is created?

example public class Program{ Program(){System.out.println("hello");} << Is this the constructor? } main... Program pgm = new Program(); < or is the constructor created here when an instance of class is created?

13th Sep 2017, 10:02 AM
D_Stark
D_Stark - avatar
6 Respostas
+ 3
The second one you wrote creates the constructor, it initializes the object pgm.
13th Sep 2017, 10:14 AM
Ziv
Ziv - avatar
+ 2
If I understand you correctly, the Program() you wrote defines a method in class Program. So maybe the term you are looking for is method
13th Sep 2017, 10:46 AM
Ziv
Ziv - avatar
+ 2
You welcome @David
13th Sep 2017, 2:03 PM
Ziv
Ziv - avatar
+ 1
thanks Ziv
13th Sep 2017, 11:57 AM
D_Stark
D_Stark - avatar
0
thanks do u know what its called in class before its initialized is it some sort of variable?
13th Sep 2017, 10:18 AM
D_Stark
D_Stark - avatar
0
simply put, a constructor is a non-static method with the same name as your class. in the class Program your constructor would be: Program(<param>), where <param> is optional and can be any type. when you type Program Pym = new Program(); this is a method call to your constructor. side note: method overloading does work here, meaning you can have multiple constructors (since they all have the same name), just change the <param> for each one. such as: Program(int I){...} Program(String message){...} so on..
13th Sep 2017, 5:21 PM
Will