一:内部类
/*
内部类
内部类的访问规则:
1,内部类可以直接访问外部类中的成员:包括私有。
之所以可以直接访问外部类中的成员,是因为内部类中持有了一个
外部类的引用,格式 外部类名.this
2,外部类要访问内部类,必须建立内部类对象。
外部其他类访问:outer out = new outer().new inner();
3,当内部类在成员位置上,就可以被成员修饰符所修饰
注意:(1),当内部类定义了静态成员,该内部类必须是static的
(2),当外部类中的静态方法访问内部类时,内部类也必须是static的
4,当描述事物时,事物的内部还有事物,该事物用内部类来描述
因为内部事务在使用外部事务的内容。
*/
class outer
{
int x = 2;
class inner//内部类
{
void function()
{
System.out.println(outer.this.x);
}
}
void method()
{
inner i = new inner();
in.function();
}
}
class Outer
{
public static void main(String[] args)
{
//直接访问内部类中的成员
outer out = new outer().new inner();
}
}
二:局部内部类
/*
局部内部类
1,不可以被成员修饰符修饰
2,可以直接访问外部类中的成员,因为还持有外部类中的引用
但是不可以访问他所在的局部中的变量。只能访问被final修饰的局部变量
注意:函数被调用进栈,调用完成出栈。
*/
class Outer
{
int x = 3;
void method(final int a)
{
final int y = 4;
class Inner
{
void function()
{
System.out.println(a);
}
}
new Inner().function();
}
}
class InnerClassDemo
{
public static void main(String[] args)
{
Outer o= new Outer();
o.method(7);
o.method(3);
//输出7,和3.不会报错!
}
}
三:匿名内部类
/*
匿名内部类:
1,匿名内部类其实就是内部类的简写格式
2,定义匿名内部类的前提:
内部类必须是继承一个类或者实现接口。
3, 匿名内部类的格式:new 父类或者接口(){定义子类的内容}
4, 其实匿名内部类就是一个匿名子类对象,而且这个对象有点胖。
可以理解带内容的对象
5,匿名内部类中定义的方法最好不超过两个!
*/
abstract class AbcDemo
{
abstract void show();
}
class Outer
{
int x = 2;
/*
class Inner extends AbsDemo
{
void show()
{
System.out.println(x);
}
}
*/
public void method()
{
//new Inner().show()
new AbsDemo()
{
void show()
{
System.out.println(x);
}
}.show();
}
}
class InnerClassDemo2
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
/*
练习
*/
class Test
{
//补足代码,通过匿名类
}
class ms
{
public static void main(String[] args)
{
Test.function();
}
}
四:练习答案
/*
练习
通过全文补全代码!
*/
interface Inter
{
void method();
}
class Test
{
//------------------------
public static Inter function()
{
return new Inter()
{
public void method()
{
System.out.println("haha");
}
}
}
//----------------------------
//补足代码,通过匿名类
}
class InnerClassIest
{
public static void main(String[] args)
{
Test.function().method();
}
}
/*
面试题
没有父类和接口用匿名内部类写一个想要的功能
*/
class Test
{
//------------------------
public static void function()
{
new Object()
{
public void method()
{
System.out.println("haha");
}
}.method();
}
//----------------------------
//补足代码,通过匿名类
}
class InnerClassIest
{
public static void main(String[] args)
{
Test.function();
}
}