开发者

Understanding syntax in Java

I can see in couple of examples on the web a new s开发者_如何学运维yntax for me, here's an example:

Accumulator<Integer> sum = new Accumulator<Integer>(){
    public Integer accumulate(Integer t1, Integer t2) {
    return t1+t2;
     }
  };

In general, what does that mean when one writes { a method } after making an instance of a class? Is it some kind of old syntax for something?

Thanks


You're creating an Anonymous inner class.

new Accumulator<Integer>() {
    @Override
    public Integer accumulate(Integer t1, Integer t2) {
        return t1 + t2;
    }
};

Defines an anonymous implementation of Accumulator. You then go on to assign a reference to this anonymous class to sum.

Think of it as a convenient way of simultaneously defining and assigning an implementation. It's a syntactic sugar.


No, this is an anonymous inner class. It has the signature of the interface or class of it's type, but can override public methods.


This is called anonymous inner class, i.e. class that does not have name and therefore may be created together with its only one instance. This is the way to decrease number of visible classes in your project when you need to implement some interface and need only one instance of such implementation.

But do not abuse this feature. Use it only if the implementation is trivial (1-2 lines).


It's an anonymous inner class which is commonly used.

A quote "An anonymous class is essentially a local class without a name."


It is either creating an anonymous subclass with an overloaded method or an anonymous interface implementation (depending on if Accululator is a class or interface).


This is an example of an anonymous class declaration.

Section 15.9.5 of the Java Language Specification discusses these types of declarations.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜