欢迎大家来到IT世界,在知识的湖畔探索吧!
前面发过一篇关于匿名类的,再次修正下
欢迎大家来到IT世界,在知识的湖畔探索吧!
匿名类是什么?
匿名类,就是没有名称的类,其名称由java编译器给出。一般是:外部类名称+$+匿名类顺序。
如何手写匿名类?
// 接口类 interface StudentInterface { String getInfo(); } @Data public class AnonymousStudent { private String no; private String name; public String getCard() { // 创建匿名类实现接口同时对其进行实例化 StudentInterface info = new StudentInterface() { @Override public String getInfo() { return no + "_" + name; } }; return info.getInfo(); } public String getCard(StudentInterface studentInterface) { return studentInterface.getInfo(); } public String getCardName() { return this.name; } public static void main(String[] args) { AnonymousStudent student = new AnonymousStudent(); student.setNo("no000001"); student.setName("name00001"); System.out.println("匿名类,接口方式一" + student.getCard()); String result = student.getCard(new StudentInterface() { @Override public String getInfo() { return student.no + student.name; } }); System.out.println("匿名类,接口方式二:" + result); System.out.println("普通方法调用:" + student.getCardName()); String name = "子名称"; AnonymousStudent childStudent = new AnonymousStudent() { @Override public String getCardName() { return super.getCardName() +"-"+ name; } }; childStudent.setName("父名称"); System.out.println("匿名类,继承父类方式:" + childStudent.getCardName()); } }
欢迎大家来到IT世界,在知识的湖畔探索吧!
匿名类有上述3种常见的实现方式。
匿名类的特征是什么?
1.匿名类可以是一种即时继承现有类的方法。
2.匿名内部类只能使用一次,不区分static和非static。如果用到外部类的变量的话,必须是类变量或者实例变量,或者final的局部变量。
3.匿名类型包含一个或多个公共只读属性,匿名内部类默认包含了外部类对象的引用。
4.可以使用匿名内部类的地方,都可以替换为内部类(单独写实现,可多次使用)。
5.匿名类没有构造器和静态成员。
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://itzsg.com/95482.html