Ankur
Ankur

Reputation: 51110

Can a Java object pass itself an instance of itself

I have a class called SomeClass which has a method called methodToCall(SomeClass o)

If I instantiate SomeClass like this:

SomeClass itsObject = new SomeClass();

Can I then do this:

itsObject.methodToCall(itsObject);

Upvotes: 4

Views: 6580

Answers (5)

Andy
Andy

Reputation: 3743

Yes, you can do this, as long as methodToCall accepts an object of type SomeClass(or a class deriving from SomeClass) as a parameter:

public void methodToCall(SomeClass parameter){.....}

You can call it from outside your class:

yourObject.methodToCall(yourObject)

or from within the class, using this :

public class SomeClass{
    ...
    public void AnotherMethod(SomeClass parameter)
    {
       this.methodToCall(this);
    }
    ...
}

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1502066

Absolutely. How that will behave will depend on the implementation, of course.

Just as an example, equals is defined to be reflexive, such that:

x.equals(x)

should always return true (assuming x is non-null).

Upvotes: 11

Jigar Joshi
Jigar Joshi

Reputation: 240928

It would be by default,
you don't need to specify it. in method body you can refer it as this

Note: method should not be static

and if you want to externally specify you can do it simple.

Upvotes: 2

Bozho
Bozho

Reputation: 597224

Yes, you can.

One (contrived) example:

BigInteger one = BigInteger.ONE;
BigInteger two = one.add(one);

(You should try these things in your IDE - it takes less time than writing a question)

Upvotes: 9

smola
smola

Reputation: 883

Yes. There is nothing that prevents you doing this.

Upvotes: 2

Related Questions