jou
jou

Reputation: 101

overriding methods without subclassing in Java

I started on a new project recently and saw the usage of overriding like below for the first time.

public class SomeClass {
  public void myMethod() {
    XStream xstream = new XStream() {
            @Override
            protected MapperWrapper wrapMapper(MapperWrapper next) {
                return new MapperWrapper(next) {
 // the rest ommitted

Basically, it's overriding the wrapMapper() method of the XStream class in the thoughtworks xstream api but without having SomeClass to extend the XStream class. I've worked with Java for a number of years but this is the first time I saw overriding being done like this. Can someone explain the ins and out of it? Thanks.

Upvotes: 10

Views: 7631

Answers (5)

Omar.Nassar
Omar.Nassar

Reputation: 379

The new implementation for

wrapMapper(MapperWrapper next)

method is limited for this instance xstream

XStream xstream

this type of overriding is creating a class that extends XStream, that's why it is called Anonymous, do not have a name and you can not have a reference for it.

Upvotes: 1

Grooveek
Grooveek

Reputation: 10094

Search Google for Anonymous Inner Class in Java

That's pretty useful to implement interfaces or abstract Class methods on concrete objects

That's heavily used when working with threading (Runnable class)

Upvotes: 0

Isaac Truett
Isaac Truett

Reputation: 8874

That's an Anonymous Inner Class.

Upvotes: 8

Vincent Cantin
Vincent Cantin

Reputation: 17302

That is called an "Anonymous class". You can find a lot of documentation about this special syntax on Internet. Good luck.

Upvotes: 0

anon
anon

Reputation:

In this case the XStream class is an anonymous inner class. Then you're overriding the method of your anonymous XStream class.

Upvotes: 2

Related Questions