12月30日 面向对象05------内部类

来源:互联网 发布:cf免费刷火麒麟软件 编辑:程序博客网 时间:2024/06/06 05:36
内部类


概述:把类定义在其他类的内部


特点:1.可以访问外部类的成员,包括私有
2.外部类如果要访问内部类,必须创建对象


位置:
1.成员位置定义的类 成员内部类
2.局部位置定义的类 局部内部类


成员内部类:
外部类名.内部类名 对象名 = 外部类对象.内部类对象;


内部类常用private修饰,保证数据的安全性。通过一个方法进行判断


为了方便访问数据,使用static修饰,用类名直接访问数据
静态内部类访问的外部类数据必须用static修饰,内部可以有静态 非静态方法
静态内部类不能直接通过外部对象访问(Warning) Outer.Inner oi = new Outer.Inner();




面试题:
要求请填空 分别输出30 20 10 
    
class Outer
{
public int num = 10;
class Inner
{
public int num = 20;
public void show()
{
int num = 30;
System.out.println(___1___);
System.out.println(___2___);
System.out.println(___3___);
}
}
}


public class Test
{
public static void main(String[] args)
{
Outer.Inner oi = new Outer().new Inner();
oi.show();
}
}


1.num
2.this.num
3.Outer.this.num


局部内部类
可以直接访问外部类的成员
在局部位置,可以创建内部类对象


面试题:
局部内部类访问局部变量的注意事项?
1.局部内部类访问局部变量必须用final修饰
2.局部变量随着方法的调用而调用,随着调用的完毕而消失,然而堆内存中的数据不会立刻消失。






匿名内部类
前提:存在一个类 或者 接口
格式:new 类名或者接口名(){重写方法;}
本质:是一个继承了该类(实现了该接口)的子类的匿名对象


interface Inter
{
public abstract void show();
public abstract void show2();
}


class Outer
{
public void method(){
/*
1个方法的时候
new Inter(){
public void show(){
System.out.println("Hello");
}
}.show();
*/
/*
有点麻烦……
new Inter(){
public void show()
{
System.out.println("show");
}
public void show2()
{
System.out.println("show2");
}
}.show();
new Inter(){
public void show()
{
System.out.println("show");
}
public void show2()
{
System.out.println("show2");
}
}.show2();
*/
/**********************************************************/
//多态
Inter in = new Inter(){
public void show()
{
System.out.println("show");
}
public void show2()
{
System.out.println("show2");
}
};
in.show();
in.show2();
}
}


public class Test
{
public static void main(String[] args)
{
Outer out = new Outer();
out.method();
}
}




匿名内部类在开发中的应用:
安卓开发常用




面试题:


//要求在控制台输出hello world
interface Inter
{
void show();
}


class Outer
{
//补全代码
}


class OuterDemo
{
public static void main(String[] args)
{
Outer.method().show();
}
}


补全的代码:
public static Inter method()
{
   return new Inter()
   {
      public void show()
      {
System.out.println("hello world");
      }
   };
}

0 0
原创粉丝点击