请考虑此代码
public class Utilities
{
public static MyClass GetMyClass()
{
MyClass cls = new MyClass();
return cls;
}
}
这个静态方法每次调用时都会返回
MyClass
的新实例吗?或者它会一遍又一遍地返回对同一实例的引用?
new 关键字在调用该方法的所有内容时创建一个新实例,并将该实例返回给调用者。 static 关键字告诉编译器该方法在类级别本身可用。调用者可以使用返回的实例。
声明一个方法
static
意味着它是一个类方法,可以在没有实例的情况下在类上调用(并且无法访问实例成员,因为上下文中没有对象可供使用 - 没有 this
)。
看下面的代码。预期输出:
[1] Different
[2] Same
如果您希望变量具有类的生命周期并每次都返回相同的对象,请在类中将变量声明为
static
:
public static String getThing(){
String r=new String("ABC");//Created every time the method is invoked.
return r;
}
private static String sr=new String("ABC");//Static member - one for the whole class.
public static String getStaticThing(){
return sr;
}
public static void main (String[] args) throws java.lang.Exception
{
String thing1=getThing();
String thing2=getThing();
if(thing1==thing2){
System.out.println("[1] Same");
}else{
System.out.println("[1] Different");
}
String thing1s=getStaticThing();
String thing2s=getStaticThing();
if(thing1s==thing2s){
System.out.println("[2] Same");
}else{
System.out.println("[2] Different");
}
}
这个静态方法每次调用时都会返回
的新实例吗?MyClass
是的。您显式创建一个返回
MyClass
的新实例。
每次调用
new MyClass()
时都会创建一个新对象,因此您可以预期它将返回一个新实例。您可以通过调用此方法两次并比较结果来检查这一点。
它既不是静态的也不是动态的。这只是一个例子。这取决于开发人员和对象的使用。
每次调用静态方法时,都会创建一个新实例。