本文共 3932 字,大约阅读时间需要 13 分钟。
java匿名类
Java anonymous class are like local class or inner class without a name. We can use java anonymous class to declare and instantiate a class at the same time.
Java匿名类就像没有名称的本地类或内部类。 我们可以使用Java匿名类同时声明和实例化一个类。
Java匿名类是嵌套或本地类。 仅当您只想使用本地类一次时,才应使用它们。 让我们看一下Java程序中的匿名类的示例。
package com.journaldev.java.examples;public interface Hello { public void sayHello();}
Hello
is an interface, let’s see how we can create an anonymous class implementation of Hello interface.
Hello
是一个接口,让我们看看如何创建Hello接口的匿名类实现。
package com.journaldev.java.examples;public class AnonymousExample { //nested anonymous class public static Hello hello = new Hello() { @Override public void sayHello() { System.out.println("Hello nested anonymous class"); } }; public static void main(String[] args) { //anonymous class inside method Hello h = new Hello() { @Override public void sayHello() { System.out.println("Hello anonymous class"); } }; h.sayHello(); AnonymousExample.hello.sayHello(); }}
Above Hello class can be an abstract class also, like below.
Hello类上方也可以是抽象类,如下所示。
package com.journaldev.java.examples;public abstract class Hello { abstract void sayHello();}
Not only that, Hello can be a normal top level class also, like below.
不仅如此,Hello也可以是普通的顶级类,如下所示。
package com.journaldev.java.examples;public class Hello { public void sayHello(){};}
Notice that anonymous classes are expressions and ends with semicolon.
请注意,匿名类是表达式,并以分号结尾。
Anonymous class is defined by calling class constructor followed by class definition code inside curly braces.
匿名类是通过在大括号内调用类构造函数和类定义代码来定义的。
Since anonymous class don’t have a name, we can’t define a constructor inside the class code body.
由于匿名类没有名称,因此我们无法在类代码主体内定义构造函数。
What if our Hello class don’t have no-args constructor? Can we access class variables in the anonymous class? Do we need to override all the methods of class in anonymous class?
如果我们的Hello类没有no-args构造函数怎么办? 我们可以访问匿名类中的类变量吗? 我们需要重写匿名类中的所有类方法吗?
Let’s answer above questions with a simple code example.
让我们用一个简单的代码示例来回答上述问题。
package com.journaldev.java.examples;public class Hello { protected String s; public Hello(String str){ this.s = str; } public void sayHello(){ System.out.println(s); }; void foo(){};}
package com.journaldev.java.examples;public class AnonymousExample { public static void main(String[] args) { //anonymous class inside method Hello h = new Hello("abc") { @Override public void sayHello() { System.out.println("Hello anonymous class "+s); } }; h.sayHello(); }}
Hello
class above, we are not required to override all the methods. However if it would have been an interface or abstract class then we have to provide implementation of all the unimplemented methods. 由于我们在上面扩展了Hello
类,因此不需要覆盖所有方法。 但是,如果它将是接口或抽象类,那么我们必须提供所有未实现方法的实现。 That’s all for anonymous class in java.
Java的匿名类就这些了。
翻译自:
java匿名类
转载地址:http://zmlzd.baihongyu.com/