Domanda

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.

È stato utile?

Soluzione

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.

Altri suggerimenti

That's called an anonymous inner class.

Given that the doThing() method has the same signature as a public method in its superclass, it overrides it.

The best way to be sure is to add the @Override annotation to the method in the subclass: the compiler will generate a compilation error if the method with this annotation doesn't override any method.

The name for this structure is Anonymous inner class

You'll find plenty of docs about these with Google

In Java all non-final instance methods are subject to override (i.e. virtual). This equally applies to inner classes, so your code overrides MyObject's doThing() method.

Yes, the doThing() method is overridden. This is equivalent to an anonymous class that is inheriting the behavior of MyObject and then overriding it.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top