javaeager
javaeager

Reputation: 21

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!

Upvotes: 1

Views: 7499

Answers (4)

dramzy
dramzy

Reputation: 1429

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.

Upvotes: 0

Nagakishore Sidde
Nagakishore Sidde

Reputation: 2737

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

Upvotes: 0

Bohemian
Bohemian

Reputation: 425418

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
}

Upvotes: 4

cm2
cm2

Reputation: 1815

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

Upvotes: 0

Related Questions