Nianliang
Nianliang

Reputation: 3066

Can not understand java statement with new operator

Normally, use new ObjClass(args) to create new object, how to understand this one?

    import org.jzy3d.plot3d.builder.Mapper;
    ......
    Mapper mapper = new Mapper() {
        public double f(double x, double y) {
            return 10 * Math.sin(x / 10) * Math.cos(y / 20) * x;
        }
    };

Upvotes: 0

Views: 74

Answers (5)

DAG
DAG

Reputation: 6994

This type of construct is called an anonymous class.

Example:

interface Mapper {
    public double f(double x, double y);
}

Mapper m = new Mapper() {
    @Override // this annotation is not mandatory, but good practice! 
    public double f(double x, double y) {
        return 10 * Math.sin(x / 10) * Math.cos(y / 20) * x;
    }
}

This would be the same as this:

public class MyMapper implements Mapper {
    @Override
    public double f(double x, double y) {
        return 10 * Math.sin(x / 10) * Math.cos(y / 20) * x;
    }
}

// and then constructing like this:
Mapper mapper = new MyMapper();

This concept/construct is handy if you want do something quick.

With Java 8 this type of things has been become even more simpler with Lambda Expressions:

Mapper mapper = () -> return 10 * Math.sin(x / 10) * Math.cos(y / 20) * x;

A good book about lambda expressions in Java 8: Lambda Reference by Angelika Langer & Klaus Kreft

Upvotes: 1

edthethird
edthethird

Reputation: 6263

You are creating a new anonymous Mapper, which contains that one method. This has the same result as defining a MyCustomMapper extends/implements Mapper containing that method.

The idea is that you use an anonymous class like this when you need a custom functionality that is relatively simple for one use case. For example, you should NOT use this mapper in any other class.

Upvotes: 1

jopa
jopa

Reputation: 1139

This code creates an instance of an anonymous class derived from Mapper and creates/overrides method f

Upvotes: 0

fge
fge

Reputation: 121750

This construct defines an anonymous class extending the Mapper class and overriding its f method.

Normally, you would annotate the overriden method with @Override (starting with Java 6).

Upvotes: 0

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

If Mapper is a class, then it creates an anonymous class that extends it. If Mapper is a final class, then this code won't compile.

If Mapper is interface, then it creates an anonymous class that implements it.

More info:

Upvotes: 5

Related Questions