1

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!

javaeager
  • 21
  • 1
  • 3

4 Answers4

4

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
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

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

cm2
  • 1,815
  • 15
  • 20
0

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");
}
}
Nagakishore Sidde
  • 2,617
  • 1
  • 16
  • 9
0

IF you mean self-referential classes in general, they are very useful for any structure where an instant of that class needs to point to neighboring instant(s) in that structure, as in graphs (like trees), linked lists, etc. As for the specific example where a static field of the same type as the enclosing class is present, this may be used in design patterns like the singleton pattern.

dramzy
  • 1,379
  • 1
  • 11
  • 25