search
HomeJavajavaTutorialBrief analysis of java anonymous inner class instances
Brief analysis of java anonymous inner class instancesDec 15, 2016 pm 12:55 PM
anonymous inner class

Anonymous classes are classes that cannot have names, so they cannot be referenced. They must be declared as part of the new statement at creation time. This requires using another form of new statement, as shown below: new This form of new statement declares a new anonymous class, which is A class extends, or implements a given interface. It also creates a new instance of that class and returns it as the result of the statement. The class to be extended and the interface to be implemented are the operands of the new statement, followed by the body of the anonymous class. If an anonymous class extends another class, its body can access the class's members, override its methods, etc., just like any other standard class. If an anonymous class implements an interface, its body must implement the interface's methods.
java code

interface pr 
{ 
void print1(); 
} 
public class noNameClass 
{ 
public pr dest() 
{ 
return new pr(){ 
public void print1() 
{ 
System.out.println("Hello world!!"); 
} 
}; 
} 
public static void main(String args[]) 
{ 
noNameClass c = new noNameClass(); 
pr hw=c.dest(); 
hw.print1(); 
} 
}

pr can also be a class, but the methods you call externally must be declared in your class or interface. Methods inside anonymous classes cannot be called from outside.
Perhaps the most commonly used place for internal anonymous classes in Java is in Listner has been added to Frame.
As follows:
java code

import java.awt.*; 
import java.awt.event.*; 
public class QFrame extends Frame { 
public QFrame() { 
this.setTitle(\"my application\"); 
addWindowListener(new WindowAdapter() { 
public void windowClosing(WindowEvent e) { 
dispose(); 
System.exit(0); 
} 
}); 
this.setBounds(10,10,200,200); 
} 
}

An internal anonymous class is to create an internal class, but it is not named for you, that is, there is no variable that refers to the instance.

new WindowAdapter() { 
public void windowClosing(WindowEvent e) { 
dispose(); 
System.exit(0); 
} 
}

new is to create a WindowAdapter object. The following {} indicates that the operation in the brackets acts on this default object, and the above Java program is followed by a function body.
The purpose of this usage is to create an instance of an object and override one of its functions. You can find it by opening the WindowAdapter code. It is an abstract class. It is an implementation of the WindowListener interface. The parameter of Frame.addWindowListner(); is a WindowListner, and the implementation is to pass an anonymous class derived from WindowAdapter.
1. How to determine the existence of an anonymous class? I can't see the name, it feels like it's just an object created by new from the parent class, and there is no name for the anonymous class.
Let’s look at the pseudocode first

abstract class Father(){ 
.... 
} 
public class Test{ 
Father f1 = new Father(){ .... } //这里就是有个匿名内部类 
}

Generally speaking, when new an object, there should be a semicolon after the parentheses, that is, the statement of new when the object ends.
But it is different when an anonymous inner class appears. The parentheses are followed by braces, and the braces contain the specific implementation method of the new object.
Because we know that an abstract class cannot be new directly. We must first have an implementation class before we can new its implementation class.
The above pseudocode means that new is the implementation class of Father. This implementation class is an anonymous inner class.
In fact, splitting the above anonymous inner class can be

class SonOne extends Father{ 
...//这里的代码和上面匿名内部类,大括号中的代码是一样的 
} 
public class Test{ 
Father f1 = new SonOne() ; 
}

2. Precautions for anonymous inner classes
Note that the declaration of the anonymous class is done at compile time, and the instantiation is done at runtime. This means that a new statement in a for loop will create several instances of the same anonymous class, rather than creating one instance of several different anonymous classes.
When using anonymous inner classes, remember the following principles:
 ·Anonymous inner classes cannot have constructors.
 ·Anonymous inner classes cannot define any static members, methods and classes.
 ·Anonymous inner classes cannot be public, protected, private, or static.
 ·Only one instance of an anonymous inner class can be created.
·An anonymous inner class must be behind new, and it is used to implicitly implement an interface or implement a class.
 ·Because anonymous inner classes are local inner classes, all restrictions on local inner classes take effect on them.
·Inner classes can only access static variables or static methods of outer classes.
This in anonymous classes and inner classes:
Sometimes, we will use some inner classes and anonymous classes. When using this in an anonymous class, this refers to the anonymous class or inner class itself. If we want to use the methods and variables of the external class at this time, we should add the class name of the external class
3. The role of anonymous inner classes
Java’s internal classes are essentially different from nested classes in C++: C++’s The nested class does not have a handle to the wrapper class. It only expresses the concept of encapsulation; but Java's inner class is different, it can access the members of the wrapping class (which means it has a handle to the wrapping class).
Anonymous inner class is a simplified way of writing inner class: return new Wrapper {
...
};
Equivalent to: Wrapped extends Wrapper {
...
}
return new Wrapped();
Is it anonymous internal Is this the only role of classes?
Consider this case:

interface ICount { 
int count(); 
} 
class Parent { 
int i = 0; 
int count() { 
return i++; 
} 
}

There is a class Child, which not only wants to inherit the count() method of Parent, but also wants to implement the count method in the ICount interface. What should we do at this time? Internal classes can show their talents:

class Child extends Parent { 
ICount getCount() { 
return new ICount { 
int i = 0; 
int count() { 
return (i *= 2); 
} 
} 
} 
}

Look at this code

public static void main(String[] args) { 
theApp = new Analyzer(); 
SwingUtilities.invokeLater(new Runnable() { // Anonymous Runnable class 
// object 
public void run() { // Run method executed in thread 
theApp.creatGUI(); // Call static GUI creator 
} 
}); 
} 
public static void main(String[] args) { 
theApp = new Analyzer(); // 创建一个对象 
SwingUtilities.invokeLater(new Runnable() { // Anonymous Runnable class 
// 一个匿名内部类,他实现了一个线程 
// 原本这个方法是传一个Runnable类型参数 // 这里可以通过这种匿名类的方式来实现 
// object 
public void run() { // Run method executed in thread 
theApp.creatGUI(); // Call static GUI creator 
} 
}); 
}



For more articles related to the brief analysis of java anonymous internal class instances, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Java 匿名内部类如何解决内存泄漏问题?Java 匿名内部类如何解决内存泄漏问题?May 01, 2024 pm 10:30 PM

匿名内部类可导致内存泄漏,问题在于它们持有外部类的引用,从而阻止外部类被垃圾回收。解决方法包括:1.使用弱引用,当外部类不再被强引用持有时,垃圾回收器会立即回收弱引用对象;2.使用软引用,垃圾回收器会在进行垃圾回收时需要内存时才回收软引用对象。在实战中,例如Android应用中,可以通过使用弱引用来解决因匿名内部类引起的内存泄漏问题,从而在不需要监听器时回收匿名内部类。

Java 匿名内部类的设计模式有哪些?Java 匿名内部类的设计模式有哪些?May 02, 2024 pm 04:42 PM

匿名内部类是Java中没有显式名称、通过new表达式创建的特殊内部类,主要用于实现特定接口或扩展抽象类,并在创建后立即使用。常见的匿名内部类设计模式包括:适配器模式:将一个接口转换为另一个接口。策略模式:定义和替换算法。观察者模式:注册观察者并处理事件。它在实际应用中非常有用,例如按字符串长度排序TreeSet、创建匿名线程等。

Java 匿名内部类有哪些优势?Java 匿名内部类有哪些优势?Apr 30, 2024 am 11:39 AM

匿名内部类在Java中作为方便创建子类、简化代码和处理事件(例如按钮单击)的特殊内部类。实战案例包括:事件处理:使用匿名内部类为按钮添加单击事件监听器。数据转换:使用Collections.sort方法和匿名内部类作为比较器对集合进行排序。

Java 匿名内部类的生命周期是怎样的?Java 匿名内部类的生命周期是怎样的?May 01, 2024 pm 04:06 PM

匿名内部类的生命周期由其作用域决定:方法局部内部类:仅在创建它的方法范围内有效。构造器内部类:与外部类实例绑定,当外部类实例释放时释放。静态内部类:与外部类同时加载卸载。

Java 匿名内部类有哪些常见错误?Java 匿名内部类有哪些常见错误?May 02, 2024 am 09:03 AM

匿名内部类使用错误:在非线程安全环境中使用捕获未声明的异常访问超出范围的变量

Java 匿名内部类如何优化性能?Java 匿名内部类如何优化性能?May 02, 2024 am 08:48 AM

匿名内部类的性能问题在于每次使用都会重新创建,可通过以下策略优化:1.将匿名内部类存储在局部变量中;2.使用非静态内部类;3.使用lambda表达式。实战测试表明lambda表达式优化效果最佳。

Java 匿名内部类的替代方案是什么?Java 匿名内部类的替代方案是什么?Apr 30, 2024 pm 01:15 PM

Lambda表达式作为匿名内部类的替代方案,提供了更简洁的方式来定义函数式接口的实现:使用简短语法(parameters)->expression定义匿名函数。适用于需要实现函数式接口(只有一个抽象方法)的场合。能够简化列表排序和线程定义等任务。

Java 匿名内部类在哪些场景下不适合使用?Java 匿名内部类在哪些场景下不适合使用?May 03, 2024 pm 05:42 PM

匿名内部类不适合使用的情况有:需要访问私有成员需要多个实例需要继承需要访问泛型类型

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools