Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is it called in Java when you create an instance on the fly?

In code,

class MyObject {
   public String doThing() {
      return "doh";
   }
}

class MyClass {
   private myObject = null;
   public MyClass() {
       myObject = new MyObject() {
           public String doThing() {
              return "huh?";
           }
       };
   }

What is it called when myObject is assigned a new object? I'm technically trying to find out if the 'doThing' overrides the method from MyObject, or if it redefines it, but I have no idea what to search on to find an answer - and no idea what question to ask without knowing what it's called when you create a new instance of an object on the fly and give it an implementation.

like image 730
Kieveli Avatar asked Dec 04 '22 18:12

Kieveli


1 Answers

You are creating an anonymous inner class that is a subclass of MyObject, so yes, you are overriding the doThing method, if is that what you ask.

By the way, anonymous classes are like named classes, they have their own bytecode in their .class file, that is named like their enclosing class suffixed with a dollar sign and an number.

If you want to experiment by yourself, you can use the method getClass() of myObject and extract information about it, like the name, parent, implemented interfaces, generic arguments, etc.

like image 144
fortran Avatar answered Dec 07 '22 08:12

fortran