search
HomeJavajavaTutorialBrief analysis of java anonymous inner class instances

Brief analysis of java anonymous inner class instances

Dec 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
How does platform independence benefit enterprise-level Java applications?How does platform independence benefit enterprise-level Java applications?May 03, 2025 am 12:23 AM

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?May 03, 2025 am 12:22 AM

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.May 03, 2025 am 12:21 AM

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

What are the benefits of Java's platform independence for developers?What are the benefits of Java's platform independence for developers?May 03, 2025 am 12:15 AM

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

What are the advantages of using Java for web applications that need to run on different servers?What are the advantages of using Java for web applications that need to run on different servers?May 03, 2025 am 12:13 AM

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)