Can a Java object pass itself on to the instance

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

If I create SomeClass as follows:

 SomeClass itsObject = new SomeClass(); 

Can I do the following:

 itsObject.methodToCall(itsObject); 
+4
source share
5 answers

That's right. How this will behave, of course, will depend on the implementation.

As an example, equals is defined as reflective, so that:

 x.equals(x) 

should always return true (assuming x not null).

+11
source

Yes, you can.

One (far-fetched) 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)

+9
source

That would be the default
you do not need to specify it. in the body of the method you can call it this

Note: the method must not be static

and if you want to specify from the outside, you can do it simply.

+2
source

Yes. There is nothing stopping you from doing this.

+2
source

Yes, you can do this as long as the ToCall method accepts an object of type SomeClass (or a class derived from SomeClass) as a parameter:

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

You can call it from outside your class:

 yourObject.methodToCall(yourObject) 

or inside the class using this:

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

All Articles