Java anonymous inner class instance code explanation
•
Java
This article mainly introduces the detailed explanation of the Java anonymous internal class example code. The example code is introduced in great detail, which has a certain reference value for everyone's study or work. Friends in need can refer to it
Person. java
package insof;
public class Person extends Object{
String name;
static int age;
public Person() {
this.name = "tom";
System.out.println("执行的是构造方法");
}
public void test(){
System.out.println("Person的test方法");
}
Main. java
package insof;
public class Main {
public static void main(String[] args) {
//匿名内部类,为Person的子类
//该类没有类名,不能显示的调用new方法来创建对象,想要初始化属性可以用代码块
Person p = new Person() {
{
super.name = "jack";
}
@Override
public void test() {
System.out.println("匿名子类");
}
};
System.out.println(p.name);
p.test();
}
}
Output:
The construction method is executed
jack
Anonymous subclass
The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
