标签:内部类
黑马程序员——java基础——内部类
------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
内部类
如果A类需要直接访问B类中的成员,而B类又需要建立A类的对象。这时,为了方便设计和访问,直接将A类定义在B类中。就可以了。A类就称为内部类。内部类可以直接访问外部类中的成员。而外部类想要访问内部类,必须要建立内部类的对象。
内部类的访问规则
1,内部类可以直接访问外部类中的成员,包括私有。
之所以可以直接访问外部类中的成员,是因为内部类中持有了一个外部类的引用,格式 外部类名.this
2,外部类要访问内部类,必须建立内部类对象。
访问格式
1,当内部类定义在外部类的成员位置上,而且非私有,可以在外部其他类中。可以直接建立内部类对象。
格式
外部类名.内部类名 变量名 = 外部类对象.内部类对象;
Outer.Inner in = new Outer().new Inner();
<span style="font-size:14px;">public class InnerClassDemo {
public static void main(String[] args)
{
// Outer out = new Outer();
// out.method();
//直接访问内部类中的成员。
Outer.Inner in = new Outer().new Inner();
in.function();
}
}
class Outer
{
private int x = 3;
class Inner//内部类
{
int x = 4;
void function()
{
int x = 6;
System.out.println("innner :"+ x );
System.out.println("innner :"+ this.x );
System.out.println("innner :"+ Outer.this.x );
}
}
void method()
{
Inner in = new Inner();
in.function();
}
}</span>
2,当内部类定义在外部类中的成员位置上,可以使用一些成员修饰符修饰 private、static。
1:默认修饰符。
直接访问内部类格式:外部类名.内部类名 变量名 = 外部类对象.内部类对象;
Outer.Inner in = new Outer.new Inner();//这种形式很少用。
但是这种应用不多见,因为内部类之所以定义在内部就是为了封装。想要获取内部类对象通常都通过外部类的方法来获取。这样可以对内部类对象进行控制。
2:私有修饰符。
通常内部类被封装,都会被私有化,因为封装性不让其他程序直接访问。
3:静态修饰符。
如果内部类被静态修饰,相当于外部类,会出现访问局限性,只能访问外部类中的静态成员。
注意;如果内部类中定义了静态成员,那么该内部类必须是静态的。
<span style="font-size:14px;">class Outer2
{
private static int x = 3;
static class Inner//静态内部类
{
static void function()
{
System.out.println("innner :"+ x);
}
}
static class Inner2
{
void show()
{
System.out.println("inner2 show");
}
}
public static void method()
{
//Inner.function();
new Inner2().show();
}
}
public class InnerClassDemo2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Outer2.method();
// Outer2.Inner.function();
// new Outer2.Inner().function();
//直接访问内部类中的成员。
Outer2.Inner in = new Outer2.Inner();
in.function();
}
}
</span>
内部类编译后的文件名为:“外部类名$内部类名.java”
为什么内部类可以直接访问外部类中的成员呢?
那是因为内部中都持有一个外部类的引用。这个是引用是外部类名.this
内部类可以定义在外部类中的成员位置上,也可以定义在外部类中的局部位置上
内部类定义在局部时
1,不可以被成员修饰符修饰
2,可以直接访问外部类中的成员,因为还持有外部类中的引用。但是不可以访问它所在的局部中的变量。只能访问被final修饰的局部变量。
<span style="font-size:14px;">public class InnerClassDemo3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Outer1 out = new Outer1();
out.method(7);
}
}
class Outer1 {
int x = 3;
void method(final int a) {
final int y = 4;
class Inner {
void function() {
System.out.println(y);
}
}
new Inner().function();
}
}</span>匿名内部类<span style="font-size:14px;">public class InnerClassDemo4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
new Outer4().function();
}
}
abstract class AbsDemo {
abstract void show();
}
class Outer4 {
int x = 3;
public void function() {
AbsDemo d = new AbsDemo() {
int num = 9;
void show() {
System.out.println("num===" + num);
}
void abc() {
System.out.println("haha");
}
};
d.show();
// d.abc();//编译失败;
}
}</span>
标签:内部类
原文地址:http://blog.csdn.net/wk843620202/article/details/45261053