class Chinese { private static Chinese object = new Chinese(); private Chinese() {} public static Chinese getInstance(){ return object; 7 } public class TestChinese{ public static void main(String[] args) { Chinese obj1 = Chinese.getInstance(); Chinese obj2 = Chinese.getInstance(); System.out.println(obj1 == obj2) ;
时间: 2024-03-05 10:51:19 浏览: 107
这段代码有误,应该是这样的:
```
class Chinese {
private static Chinese object = new Chinese();
private Chinese() {}
public static Chinese getInstance() {
return object;
}
}
public class TestChinese {
public static void main(String[] args) {
Chinese obj1 = Chinese.getInstance();
Chinese obj2 = Chinese.getInstance();
System.out.println(obj1 == obj2);
}
}
```
这段代码的输出结果是:true。
因为在 Chinese 类中,构造方法被私有化了,所以外部无法通过 new 关键字创建对象。而 getInstance() 方法返回了一个类内部创建的静态对象 object,所以 obj1 和 obj2 引用的是同一个对象。因此,obj1 == obj2 的结果为 true。
相关问题
getInstance
`getInstance` is a commonly used static method in object-oriented programming that returns a single instance of a class. This method ensures that only one instance of the class is created and it provides a global point of access to that instance.
For example, in the Singleton design pattern, `getInstance` is used to create a single instance of a class and to provide access to that instance throughout the application.
Here's an example implementation of the `getInstance` method:
```java
public class Singleton {
private static Singleton instance = null;
private Singleton() {
// private constructor to prevent instantiation outside of class
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
```
In this example, the `Singleton` class has a private constructor to prevent instantiation outside of the class. The `getInstance` method checks whether an instance of the class already exists and creates one if it does not. It then returns the existing or newly created instance.
阅读全文