匿名内部类:
- 匿名内部类歧视就是内部类的简写格式。
- 定义内部类的前提:
内部类必须是继承一个类或者实现接口。 - 匿名内部类的格式:new 父类或者接口(){定义子类的内容}
- 其实匿名内部类就是一个匿名子类对象,而且这个对象有点胖,可以理解为带内容的对象。
- 匿名内部类中定义的方法最好不要超过三个。
public class Outer {
int x = 3;
public void function()
{
new AbsDemo() //new 类().对象方法();
{
@Override
void show() {
System.out.println("x = " + x);
}
}.show();
}
}
abstract class AbsDemo
{
abstract void show();
}
public class Outer {
int x = 3;
public void function()
{
AbsDemo d = new AbsDemo() //new 类().对象方法(); 多态
{
@Override
void show() {
System.out.println("x = " + x);
}
void abc()
{
System.out.println("hehe");
}
};
d.show();
// d.abs(); 编译失败,因为引用只能调用父类中的方法,不能调用子类中的特有方法
}
}
class TestDemo{
public static void main(String[] args) {
new Outer().function();
}
}
静态:
interface Inter {
void method();
}
class Test
{
//实现
static class Inner implements Inter
{
public void method()
{
System.out.println("method run");
}
}
static Inter function()
{
return new Inner();
}
//结束
}
class InnerClassTest
{
public static void main(String[] args) {
Test.function().method(); //条件
}
}
Outer.this.x;
this.x;
改写:
interface Inter {
void method();
}
class Test
{
//实现:
static Inter function()
{
return new Inter()
{
public void method()
{
System.out.println("method run");
}
};
}
//结束
}
class InnerClassTest
{
public static void main(String[] args) {
/*
Test.funtion():Test类中有一个静态方法function.
.method():function这个方法运算后的结果是一个对象,而且是一个Inter类型的对象。
因为只有是Inter类型的对象,才可以调用method方法。
*/
Test.function().method(); //条件
/*
等价于
Inter in = Test.function();
in.method();
*/
}
}
interface Inter {
void method();
}
class InnerClassTest
{
public static void main(String[] args) {
show(new Inter()
{
public void method()
{
System.out.println("method run");
}
});
}
public static void show(Inter in)
{
in.method();
}
}
new Object(); //创建一个Object对象
new Object(){
} //创建一个Object子类对象
class Test
{
public static void main(String[] args) {
new Object()
{
public void function()
{
System.out.println("function run");
}
}.function(); //调用一个方法
}
}
class Test
{
public static void main(String[] args) {
Object o = new Object()
{
public void function()
{
System.out.println("function run");
}
public void method()
{
System.out.println("method run");
}
}; //调用2个以上方法,起个名字
o.function(); //这个是错的,因为父类中没有这个方法,不能调用
o.method(); //这个是错的,因为父类中没有这个方法,不能调用
}
}
匿名内部类可以创建父类或者父接口的引用指向子类(匿名内部类),多态。