Zahra
Zahra

Reputation: 7207

Does Java allow use of an instance of the current class in its definition?

Does Java allow the use of an instance of the current class in its definition?

Example:

public class Component
{
    Component()
    {
       // some code 
    }

    public void method()
    {
        Component comp=new Component();
        // some code
    }
 }

I know that it does not result in compile-time errors. I find the self-reference a bit confusing though. Does it mean that Java's semantics allows cyclic definition of classes?

Upvotes: 1

Views: 895

Answers (3)

Alex Kreutznaer
Alex Kreutznaer

Reputation: 1170

It's not a cyclic definition.

Cyclic definition is when two or more classes reference each other in a cyclic manner. But even that would compile, though may lead to execution problems.

It is rather a "use ahead" definition, this is how I would call it.

You define a class and in its method you use a reference to the same class.

It is a bit contradictory - before you use a class you should completely define it. A method of a class is a part of its definition. Where as in a method you reference a class instance as if the class was already defined.

I agree it is confusing, but Java let you do this.

Think of a singleton.

Often there is a static method that returns the class instance. The same problem.

Upvotes: 0

Cengiz
Cengiz

Reputation: 4867

i think you thought about something like this... Running this leads to

Exception in thread "main" java.lang.StackOverflowError

public class AClass {

    private AClass aClass;

    public AClass() {
        this.aClass = new AClass();
        this.aClass.printHello();
    }

    private void printHello() {
        System.out.println("Hello");
    }

    public static void main(final String[] args) {
        new AClass();
    }
}

I've not needed recursive code like this. But i think there could be some use cases. It is important to have an abort criteria to prevent endless loop and the StackOverflowError.

To answer your question, i would say Java allows cylic instantiation.

Upvotes: 2

albertein
albertein

Reputation: 27130

It's perfectly legal to use / create instance of the same type on the defining class, there is no cyclic definition added.

Compilers usually do a first pass examining all the methods on a class, the actual method implementation code generation is done later once the compiler knows about all the methods available on all the clases.

Upvotes: 0

Related Questions