匿名类
1.和类有关的匿名类
A. 当某个类用abstract修饰时,但它没有子类继承并实现其内部的abstract方法,此时可以在主类中用该类构造对象的同时,实现
该类中的abstract方法
B. 当类1中的某个方法的参数是类2类型时,此时在主类中用类1创建对象并调用该方法时,在调用的同时可以重写类2中的方法
eg: class Cubic
{
double getCubic(int n)
{
return 0;
}
}
abstract class Sqrt
{
abstract double getSqrt(int m);
}
class A
{
void f(Cubic cubic)
{
System.out.println(cubic.getCubic(3));
}
}
public class class5_2
{
public statci void main(String args[])
{
A aa=new A();
Cubic cub=new Cubic();
aa.f(cub);
aa.f(new Cubic()
{
double getCubic(int n)
{
return n*n*n;
}
});
Sqrt sqrt=new Sqrt()
{
double getSqrt(int m)
{
return m*m;
}
};
System.out.println(sqrt.getSqrt(10));
}
}
运行以后的结果为:
0
27
100
2.和接口有关的匿名类
A. 当类1中的某个方法的参数是接口1类型,而接口1又没有子类继承时,此时在主类中用类1创建对象并调用该方法时,在调用的同时
可以实现接口中的全部方法
B. 如果某个接口没有子类来实现其内部的方法时,可以在主类中用该接口创建该接口对象的同时实现接口中的所有方法
eg:
interface Cubic1
{
double getCubic1(int n);
}
interface Sqrt1
{
double getSqrt1(int x);
}
class A1
{
void f(Cubic1 cubic)
{
System.out.println(cubic.getCubic(3));
}
}
public class class2 {
public static void main(String[] args)
{
A1 a=new A1();
a.f(new Cubic1()
{
double getCubic(int n)
{
return n*n*n;
}
});
Sqrt1 ss=new Sqrt1()
{
double getSqrt(int x)
{
return x*x;
}
};
System.out.println(ss.getSqrt(10));
}
}
运行以后的结果为:
27
100