class Temp
{
private Temp(int data)
{
System.out.printf(" Constructor called ");
}
protected static Temp create(int data)
{Temp obj = new Temp(data);
return obj;
}
public void myMethod()
{
System.out.printf(" Method called ");
}
}
public class Test
{
public static void main(String[] args)
{
Temp obj = Temp.create(20); //How this is a method call?
obj.myMethod();
}
}
A static
method means that it can be called without creating an Object of that class, in your example Temp
item.
static Temp create(int data)
The static
word in your method is what is allowing you to do that. The method is then callable in a static way, which means using className.methodName , in your example, Temp.create()
And since your method is returning a Temp
object, you are putting that into a Temp object
Temp obj = Temp.create(20);
In the Temp obj
you are putting the result of the object created in your method, in the line
{Temp obj = new Temp(data);
return obj; //this is your object
}
class Temp
{
private Temp(int data)
{
System.out.printf(" Constructor called ");
}
protected static Temp create(int data)
{Temp obj = new Temp(data);
return obj;
}
public void myMethod()
{
System.out.printf(" Method called ");
}
}
public class Test
{
public static void main(String[] args)
{
Temp obj = Temp.create(20); //How this is a method call?
obj.myMethod();
}
}
A constructor of a class always follows a same signature: [access modifier -> protected, public, private, default] [name of the class] (parameters)
So, in your code,
private Temp(int data) {
System.out.printf(" Constructor called ");
}
is your constructor.
In order to use your Temp
class, at least the non-static members of it, you'll need an instance of the class to be able to use it, but, since your constructor is declared private, an instance can only be created within the very same class.
That is what you do here:
protected static Temp create(int data)
{Temp obj = new Temp(data);
return obj;
}
This method is a static method, meaning it 'exists' as soon as the class is loaded in the memory, even without the class being instantiated. Since it is declared protected, not private, it can be used by subclasses of Temp
, and by classes that are in the same package as Temp
, like your Test
class.
Your Test
class calls this method, which calls the constructor, and returns the created instance to the Test
class. This way of working is used in certain scenario's, for instance if you want to limit the number of instances created per VM, like with the Singleton
pattern.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.