public class TestJava{
}
interface A{
public void printInfo();
}
class B implements A{
public void printInfo(){
System.out.println("Hello");
}
}
class X{
public void fun1(){
this.fun2(new B());
}
public void fun2(A a){
a.printInfo();
}
}
class Demo{
public static void main(String[] args){
new X().fun1();
}
}//Demo
若class B只使用一次,会不会觉得定义一个类有点浪费。
可以用匿名内部类实现接口,再传入X中的方法中。
public class TestJava{
}
interface A{
public void printInfo();
}
class X{
public void fun1(){
this.fun2(new A(){
public void printInfo(){
System.out.println("Hello!");
}
});
}
public void fun2(A a){
a.printInfo();
}
}
class Demo{
public static void main(String[] args){
new X().fun1();
}
}//Demo
第一步:直接实例化接口对象
new A{}
第二步:接口本身是不能直接进行实例化的,所以在接口实例化后要有一个大括号,在其中编写具体的实现方法。
new A{
public void println(){
System.out.println("Hello!");
}
}
大括号内实现结束后,实际上就是一个接口的实例化对象了,其中的抽象方法也实现了。
匿名对象就是没有明确给出名字的对象。
一般匿名对象只使用一次,而且匿名对象只在堆内存中开辟空间,而不存在栈内存的引用。
既然不存在栈内存的引用,所以通常用完就等待被回收。
内部类可以声明为public或private,对其访问限制与属性和方法一样。
用static可以声明内部类,不过static声明的内部类不能访问非static的外部类属性。
可以访问static声明的私有类型属性
一个内部类除了可以通过外部类访问,也可以直接在其他类中进行调用。
在方法中也可以定义内部类,不过定义在方法中的内部类不能直接访问方法中的参数,
如果方法中的参数要想被内部类访问,需要在参数前加上修饰符final
public class TestJava{
}
class Outer{
private String info = "Hello";
private static String infoS ="Hello Static";
class Inner01{
public void tell01(){
System.out.println(info);
}
}
static class Inner02{
public void tell02(){
System.out.println(infoS);
}
}
public void fun01(){
new Inner01().tell01();
}
public void fun02(final int temp){
class Inner03{
public void tell03(){
System.out.println("Attribute in the Inner03:"+info);
System.out.println("Parameter in the fun02:"+temp);
}
}
new Inner03().tell03();
}
}
class Demo{
public static void main(String[] args){
new Outer().fun01();
new Outer.Inner02().tell02();
Outer out = new Outer();
Outer.Inner01 outIn = out.new Inner01();
outIn.tell01();
new Outer().fun02(50);
}
}//Demo
输出:
Hello
Hello Static
Hello
Attribute in the Inner03:Hello
Parameter in the fun02:50