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!

1
  • 1
    @RyanJ other way around: you can't access non-static from static code. Commented Oct 18, 2014 at 2:39

4 Answers 4

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
}
Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

No. OP has a static field, not an instance.
I thought the 'conceptual' problem meant the general construct, not specifically referencing the static'ness of the field.
A linked list needs an instance field (ie non static) to hold a reference to the next node.
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");
}
}

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.