什么是匿名内部类

kkfvjmtd 2009-03-15 05:42:52
大家给我写个简单的例子,以及有什么注意事项
...全文
582 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
sunsea08 2009-03-16
  • 打赏
  • 举报
回复
//匿名类是特殊内部类,没有名字
public class A
{
A()
{
System.out.println("default constructor");
}
void method()
{
System.out.println("from A");
}
public static void main(String args[])
{
new A().method();

A a=new A() //匿名类
{
//本身没有构造方法
{
System.out.println("initialize instance");//可以实例初始化
}
void method()
{
System.out.println("from anonymous");
}
};
a.method();
}
}
steryzone 2009-03-16
  • 打赏
  • 举报
回复
1楼的不对的吗?
为什么每个人都说2楼的对呢?奇怪。。。
dreamhunter_lan 2009-03-15
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 kkfvjmtd 的回复:]
2楼的对不对呀?这么简单?
[/Quote]
那是一个简单的匿名内部类
找本书看,或上网找相关的东西看更好
kkfvjmtd 2009-03-15
  • 打赏
  • 举报
回复
2楼的对不对呀?这么简单?
猿敲月下码 2009-03-15
  • 打赏
  • 举报
回复
btnUpdate.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
btnGet2.setText(((JButton)e.getSource()).getText());
}
});

事件监听也用的上
java_coding 2009-03-15
  • 打赏
  • 举报
回复
btn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
getAppletContext().showDocument(
new URL("http://localhost/postinfo.html"),"_blank");
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
});

这个applet小程序的按钮增加了一个事件监听器,用的就是匿名的内部类。
sunxyz86 2009-03-15
  • 打赏
  • 举报
回复
lss是对的
有的时候这个类只需要用一次,所以就懒得再命名它了,可以简化代码
delphiPB 2009-03-15
  • 打赏
  • 举报
回复
楼上正解
dreamhunter_lan 2009-03-15
  • 打赏
  • 举报
回复
只会给一个例子,注意事项不是很懂~

public class Test {
public static void main(String[] args) {
Thread t = new Thread() {
private int i = 0;
public void run() {
while(true) {
System.out.println("i = " + i++);
}
}
};
t.start();
}
}
CNNRNNCNNRNN 2009-03-15
  • 打赏
  • 举报
回复
public class Parcel6 {
public Contents cont() {
return new Contents() {
private int i = 11;
public int value() { return i; }
}; // Semicolon required in this case
}
public static void main(String[] args) {
Parcel6 p = new Parcel6();
Contents c = p.cont();
}
} ///:~

62,616

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧