M
M
Mikhri2021-01-21 13:06:01
Java
Mikhri, 2021-01-21 13:06:01

How in Java to refer to the name of an instance of a class in a method located in the body of the same class?

What I mean:

Let's say there is a Dog class within the same package:

package tpack;
public class Dog {
    String name;
    public Dog (String name) {
        this.name=name;
    }
    public void bark() {
        System.out.println(name + " says: 'Woof-woof!'");
    }
}

And there is main:
package tpack;
public class Main {
  public static void main (String[] args) { 
            Dog dog1 = new Dog("Butch");
            dog1.bark();
  }
}

In this example, the output when running main is:
Butch says: 'Woof-woof!'


And I need it to be:
dog1 says: 'Woof-woof!'

but without changing anything in main.

Those. I need to somehow indicate inside the Dog class itself that when the .bark() method is called, I want to see as a result of its work the name of the specific object of the Dog class from which this .bark() is called.

Is it possible to do this, and if so, how?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2021-01-21
@Mikhri

It's impossible to do so.

the name of the specific Dog class object from which this .bark() is called

The object has no name. There is a variable that contains a reference to an object, this variable has a name at the compilation stage. There are no variable names in bytecode. References to the same object can be in different variables, and even in an array.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question