jetpack01
jetpack01

Reputation: 71

Why to use variables of the same type of the current class in which they are?

I just found a Java example that uses variables typed as the current class itself. I can't understand why and when to use something like this! It's not explained by the author of the book because it's just a part of code of an example about other stuff! Could anyone help me to understand the utility of this approach? Is it related to something like "Singleton design pattern"? Furthermore I also tried to instantiate test1 and test2 but I got an error!

public class Test {
    public Test() {
        Test test1;
        Test test2;
    }
}

The original snippet is about nested classes:

public class Tree {

    ExampleNode master;

    public Tree() {
    }

    //...
    class ExampleNode {
        ExampleNode rightNode;
        ExampleNode leftNode;

        //...
        void printMaster() {
            System.out.println( master );
        }
    }
}

Upvotes: 1

Views: 72

Answers (3)

Daniel Uribe
Daniel Uribe

Reputation: 778

The one you need to instatiate is Test. As i see there's no relation with Singleton pattern, don't you miss any code?

Upvotes: 0

Tapas Bose
Tapas Bose

Reputation: 29816

Use can create object of a class inside that class to call a class method. Consider the following example:

public class SomeClass {
  public void callMethod() {

  }

  public static void main(String... args) {
    SomeClass sc = new SomeClass();
    sc.callMethod();
  }
}

We cannot call a non static or instance method from a static method without using the instance of the class where the method belongs to. Right?

There is no relation with Singleton Pattern.

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272537

A simple example of where this would be useful is in a linked list, where each node needs a reference to its neighbour(s).

Upvotes: 7

Related Questions