What is it called in Java when you instantiate 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 called when a new object is assigned to myObject? I'm technically trying to find out if the โ€œdoThingโ€ method cancels from MyObject, or if it overrides it, but I donโ€™t know what to look for in order to find the answer - and I donโ€™t know what question to ask, not knowing what it is called when creating a new instance object "on the fly" and gives it implementation.

+4
source share
5 answers

You create an anonymous inner class that is a subclass of MyObject , so yes, you override the doThing method if that is what you are asking for.

By the way, anonymous classes are similar to named classes, they have their own bytecode in their .class file, which is named as their spanning class with a dollar suffix and a number.

If you want to experiment yourself, you can use the getClass() of MyObject method and extract information about it, for example, name, parent, implemented interfaces, general arguments, etc.

+9
source

This is called an anonymous inner class.

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

The best way to ensure that you add the @Override annotation to a method in a subclass: the compiler will generate a compilation error if a method with this annotation does not cancel any method.

+3
source

The name of this structure is Anonymous Inner Class

You will find many documents about this with Google.

+2
source

In Java, all methods of unfinished instances are subject to redefinition (i.e. virtual). This applies equally to inner classes, so your code overrides the MyObject doThing() method.

+1
source

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

+1
source

Source: https://habr.com/ru/post/1391651/


All Articles