/*匿名内部类:
临时继承某个类或操作某个接口并建立实例的需求,
使用内部类解决需求;
语法:
new 父类() | 接口 () {
// 类本体操作
};
Object o = new Object(){
//继承Object 重新定义toString() 并直接产生实例;
@Override
public String toString() {
return ("123");
}
};
如果要操作某个接口,例如若Some接口定义了doService()方法,
要建立匿名类实例,
Some some = new some(){
public void doService(){
System.out.println("Do Something For You");
}
}; //一定要注意有分号的存在。
从JDK8开始 若接口定义一个抽象方法
可以使用 Lambda 表达式 来简化 程序撰写;
如上 可以写成:
Some some = () -> {
out.println("Do Something For You");
}; 注意二者的不同。
Some some =() ->{
out.println("Do Something For You");
};
package com.dayuanit.atm.test;
import com.dayuanit.atm.service.AtmService2;
import com.dayuanit.atm.service.impl.AtmServiceImpl2;
public class TestAtm3 {
public static void main(String[] args) {
final AtmService2 atm = new AtmServiceImpl2();
new Thread(new Runnable(){
@Override
public void run() {
// atm.openAccount();
atm.deposit(40, "4122");
}
}, "老公存钱" ).start();
new Thread(new Runnable(){
@Override
public void run() {
atm.draw(200, "2999");
}
}, "老婆取钱" ).start();
}
}
最近写程序的一个匿名内部类的使用案例如上,重写Runnable接口里的方法,注意这种方式对于使用一次的情况写比较简捷。
package com.dayuanit.animal;
public abstract class Dog {
public abstract void eat();
}
package com.dayuanit.animal;
public interface Worm {
abstract void fly();
}
package com.dayuanit.animal;
public class Animal {
static int age = 20;
String name = "Animal";
static {
System.out.println(" 静态内部类来调 ");
}
// 静态代码块最先执行;
static void move() {
System.out.println(" Animal move.... ");
}
class Cat { // 内部类
int catAge = 100;
String name = "Cat";
void run() {
move();
System.out.println(" Cat running.... " + age + name);
}
}
static class Fish {
static String color = "yello";
static void move() {
System.out.println(" Fish swimming.... " + age);
}
}
public void run() {
Fish f = new Fish();
f.move();
Cat c = new Cat();
System.out.println(c.name);
}
}
举个实例 代码贴上
package com.dayuanit.animal;
public class Test {
public static void main(String[] args) {
Animal animal = new Animal();
animal.run(); // Animal类调用本类的方法
Animal.Cat cat = new Animal().new Cat();
cat.run(); // Animal类的内部类调用内部类独有的方法run() run()方法中有Animal类中的方法move();
// 内部类调用外部方法;
Animal.Fish.move(); // 直接调用内部类中的方法; . 代表 内部的方法或者属性调用
Dog dog = new Dog() { // 匿名内部类的练习 重写dog类来产生实例
public void eat() {
System.out.println("dog eating");
}
};
dog.eat();
Worm worm = new Worm() { // 匿名内部类的练习 worm接口的实例;
public void fly() {
System.out.println("Worm flying....");
}
};
worm.fly();
}
}