静态方法返回的值是静态的吗?

问题描述 投票:0回答:5

请考虑此代码

public class Utilities
{
     public static MyClass GetMyClass()
     {
          MyClass cls = new MyClass();
          return cls;
     }
}

这个静态方法每次调用时都会返回

MyClass
的新实例吗?或者它会一遍又一遍地返回对同一实例的引用?

java methods static
5个回答
3
投票

new 关键字在调用该方法的所有内容时创建一个新实例,并将该实例返回给调用者。 static 关键字告诉编译器该方法在类级别本身可用。调用者可以使用返回的实例。


0
投票

声明一个方法

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");
    }
}

0
投票

这个静态方法每次调用时都会返回

MyClass
的新实例吗?

是的。您显式创建一个返回

MyClass
的新实例。


0
投票

每次调用

new MyClass()
时都会创建一个新对象,因此您可以预期它将返回一个新实例。您可以通过调用此方法两次并比较结果来检查这一点。


0
投票

它既不是静态的也不是动态的。这只是一个例子。这取决于开发人员和对象的使用。

每次调用静态方法时,都会创建一个新实例。

© www.soinside.com 2019 - 2024. All rights reserved.