+ 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?
6 Antworten
+ 3
The second one you wrote creates the constructor, it initializes the object pgm.
+ 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
+ 2
You welcome @David
+ 1
thanks Ziv
0
thanks do u know what its called in class before its initialized is it some sort of variable?
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..