1

I am creating a method for an object in java, but I would like to use the object I'm in as parameter. So for example:

public void method1(String name)
{
     example = new object2(name, object1);
}  

Where object1 should be the object I'm calling the method from. So I want to create a new object of another class, and this class will use this object as parameter.

I tried to find if there's already a question about this, but couldn't find it. I read other questions (~10) to see if they contained what I needed, but they didn't. If anyone does find a duplicate, would he / she be kind enough to also explain what search they used?

Evelyn
  • 13
  • 4
  • Object can be used as parameters as primitive types, there is nothing special to it. – NiVeR Jul 05 '18 at 18:39
  • Also noteworthy: [Is passing 'this' in a method call accepted practice in java](https://stackoverflow.com/questions/17441871/is-passing-this-in-a-method-call-accepted-practice-in-java) – LuCio Jul 05 '18 at 19:45

2 Answers2

4

In Java, the object you are in (the one found before the dot of the method call), is referenced by the keyword this. So, your example would become:

public void method1(String name)
{
     example = new object2(name, this);
}

Then if you call myObject.method1("Peter"), the myObject from the calling place becomes this inside your method.

Ralf Kleberhoff
  • 6,990
  • 1
  • 13
  • 7
  • [This](https://en.wikipedia.org/wiki/List_of_Java_keywords), probably, will help question owner. – KunLun Jul 05 '18 at 19:34
0

There is a good pattern under the theme of your question. It's a Decorator pattern https://en.wikipedia.org/wiki/Decorator_pattern.

Andrii Torzhkov
  • 271
  • 1
  • 5
  • 15