简体   繁体   中英

Java : object of a class as instance variable in same class

Being a beginner, I have a conceptual doubt. What is the use of a class type object as member/instance variable in the same class? Something like this :

class MyClass {

static MyClass ref;
String[] arguments;

public static void main(String[] args) {
    ref = new MyClass();
    ref.func(args);
}

public void func(String[] args) {
    ref.arguments = args;
}

}

Thanks in advance!

This is used in the singleton pattern :

class MyClass {
    private static final MyClass INSTANCE = new MyClass();
    private MyClass() {}
    public static MyClass getInstance() {
        return INSTANCE;
    }
    // instance methods omitted
}

The general case of having a class have a member/attribute that is of the same class is often used. One example is for implementing linked lists

The only use that I can see is to invoke any instance methods of the same class from the static methods with out re-creating the object again and again. Something like as follows...

public class MyClass {

static MyClass ref;
String[] arguments;

public static void main(String[] args) {
    ref = new MyClass();
    func1();
    func2();
}

public static void func1() {
    ref.func();
}

public static void func2() {
    ref.func();
}

public void func() {
    System.out.println("Invoking instance method func");
}
}

如果您一般是指自引用类,则它们对于该类的瞬时需要指向该结构中的相邻瞬时的任何结构(例如图形(如树),链接列表等)非常有用。对于其中存在与封闭类具有相同类型的静态字段的特定示例,可以在设计模式(如单例模式)中使用它。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM