java中Anonymous类的用例和优点是什么? [英] What is the use case and advantage of Anonymous class in java?

查看:151
本文介绍了java中Anonymous类的用例和优点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Anonymous类的了解是,当您拥有任何类或接口时,仅某些代码需要实现或重写一些类或接口Anonymous,这增加了程序的可读性.但是我有点困惑,认为将来您需要为不同的类实现相同的接口,因此在这种情况下,您必须重构您的上一类,那么匿名类还有其他优点吗((它可以提高性能吗?)

What i know about Anonymous class is when you have any class or interface , and only someof your code need to implement or override some class or interface Anonymously ,it increases the readability of program . But i am Little bit confused suppose in future you need to implement same interface for different class , so in that case you have to refactor you previous class , so is there any other advanrage of Anonymous class ?(Is it improves performance ?)

推荐答案

这是什么意思?

匿名类就是其名称的实现方式-它没有名称.它将类declaration与该类的instance的创建结合在一起. 由于匿名类没有名称,因此无法从定义匿名类的类外部实例化对象.实际上,匿名对象只能在定义它的相同范围内实例化.

An anonymous class is just what its name imples -- it has no name. It combines the class declaration and the creation of an instance of the class in one step. Since anonymous classes have no name, objects can not be instantiated from outside the class in which the anonymous class is defined. In fact, an anonymous object can only be instantiated from within the same scope in which it is defined.

为什么要使用匿名课程?

匿名类可以节省时间,并减少定义应用程序所需的.java文件数量.您可能拥有仅在特定情况下使用的类,例如Comparator.这样可以动态"创建对象.

Anonymous classes can be time-savers and reduce the number of .java files necessary to define an application. You may have a class that is only used in a specific situation such as a Comparator. This allows an "on the fly" creation of an object.

您可能会发现自己更喜欢使用匿名类;许多人广泛使用它们在GUIs上实现listeners.

You may find you prefer to use anonymous classes; many people use them extensively to implement listeners on GUIs.

匿名类定义的语法

此示例演示了比较器的匿名类定义,该定义传递给Collections类中的sort()方法.假定aList是要排序的有效数据列表.

This example demonstrates an anonymous class definition for a comparator that is passed to the sort() method in the Collections class. Assume that aList is a valid List of data that is to be sorted.

Collections.sort (aList, 
    new Comparator () { // implements the IF 
        public int compare (ObjectType o1, ObjectType o2 ) throws ..{ 
            //.... implementation for compare() 
        } // end of compare() 
    } // end of Comparator implementation
); // closed paren for sort() and end of statement semicolon

规则:

匿名类必须始终扩展超类或实现接口,但不能具有显式的extends或Implements子句.

An anonymous class must always extend a super class or implement an interface but it cannot have an explicit extends or implements clause.

匿名类必须在超类或接口中实现所有抽象方法.

An anonymous class must implement all the abstract methods in the super class or the interface.

匿名类始终使用父类中的默认构造函数来创建实例.

An anonymous class always uses the default constructor from the super class to create an instance.

这篇关于java中Anonymous类的用例和优点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆