Home > Java > javaTutorial > body text

Brief analysis of java anonymous inner class instances

高洛峰
Release: 2016-12-15 12:55:54
Original
1273 people have browsed it

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(); 
} 
}
Copy after login

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); 
} 
}
Copy after login

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); 
} 
}
Copy after login

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(){ .... } //这里就是有个匿名内部类 
}
Copy after login

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() ; 
}
Copy after login

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++; 
} 
}
Copy after login

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); 
} 
} 
} 
}
Copy after login

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 
} 
}); 
}
Copy after login



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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template