您的位置:首页 > 职场人生

黑马程序员——JAVA笔记——内部类

2015-06-21 09:56 507 查看
------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

 当描述事物,事物的内部还有事物,该事物用内部类来描述。
  因为内部事物在使用外部事物的内容。

class Body

{

  private class XinZang
{

 
}
public void show()
{
new XinZang()
}

 }

public class Demo {
public static void main(String[] args){
Outer ou=new Outer();
ou.method();
//		直接访问内部类成员。
//		Outer.Inner oi= new Outer().new Inner();
//		oi.function();
//		内部类方法为静态
//		Outer.Inner.function();
//		内部类方法非静态
//		new Outer.Inner().function();
}
}

class Outer
{
private static int x=3;
static class Inner
{
//		int x=4;
static void function()
{
//			int x=6;
System.out.println("inner:"+x);
//			System.out.println("inner:"+this.x);
//			System.out.println("inner:"+Outer.this.x);
}
}
class Inner2
{
void show()
{
System.out.println("Inner2 show.");
}
}
void method()
{
//		Inner in=new Inner();
//		in.function();
Inner.function();
}
}


局部内部类不能修饰成员
可以直接访问外部类中的成员,因为还持有外部类中的引用。
但是不可以访问它所在的局部中的变量,只能访问被final修饰的局部变量。
public class Demo {
public static void main(String[] args){
//		new Outer().method();
Outer ou=new Outer();
ou.method(8);
ou.method(9);
}
}

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();
}
}


匿名内部类
1.匿名内部类其实就是内部类的简写格式。

2.定义匿名内部类的前提:内部类必须继承一个类或实现借口。

3.匿名内部类的格式:new 父类或者借口(){定义自雷的内容};

4.其实匿名内部类就是一个匿名子类对象。而且这个对象有点胖。可以理解为带内容的对象。

5.匿名内部类中定义的方法最好不要超过3个。

abstract class AbsDemo
{
abstract void show();
}

class Outer
{
int x=3;
/*
class Inner extends AbsDemo
{
void show()
{
System.out.println("show:"+x);
}
}
*/
void function()
{
//直接匿名调用
new AbsDemo()
{
void show()
{
System.out.println("show:"+x);
}
}.show();

//用父类创建子类对象
AbsDemo d=new AbsDemo()
{
void show()
{
System.out.println("show:"+x);
}
//			void abc()
//			{
//				System.out.println("haha");
//			}
};
d.show();
//		d.abc();//编译失败,父类中没有。
}
}


练习:
1、无父类无借口写匿名内部类
new Object(){
void function(){
System.out.println("function");
}
}.function();
2、补足代码,利用匿名内部类
public class Demo
{
public static void main(String[] args)
{
Test.function().method();
}
}

interface Inter
{
public abstract void method();
}

class Test
{
//补足代码。通过匿名内部类。
}


解:
public class Demo
{
public static void main(String[] args)
{
//Test.function():Test类中有一个静态的方法function.
//.method():function这个方法运算后的结果是一个对象。而且是一个Inter类型的对象。
//因为只有Inter类型的对象(子类),才可以调用method。
Test.function().method();
//		Inter in=Test.function();
//		in.method();
}
}

interface Inter
{
public abstract void method();
}

class Test
{
//补足代码。通过匿名内部类。

//	static class Inner implements Inter
//		{
//			public void method(){
//				System.out.println("method");
//			}
//		}
static Inter function(){
return new Inter()
{
public void method(){
System.out.println("method");
}
};

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 黑马程序员