java中内部类测试总结

来源:互联网 发布:2017教师网络研修网 编辑:程序博客网 时间:2024/05/16 14:38
public class InnerClass {
 static Toy toy = new Toy(){
  String name = "老吴";
  @Override
  public void jump()
  {
   System.out.println(name+"跳出地球");
   go();
  }
  public void go(){
   System.out.println("奔跑");
  }
 };
/*内部类:定义在类的内部的类
 *1.成员内部类:
 *1.1成员内部类可以直接访问外部类的属性
 *1.2通过  外部类名.this 这种方式访问外部类的当前对象
 *成员内部类实例化对象: 外部类名.内部类名 引用名 = 外部类对象.new 内部类名();
 *2.静态内部类
 *2.1静态内部类内部不能访问外部类的成员资源,只能通过类名访问外部类的静态资源
 *静态内部类实例化对象: 外部类名.内部类名 引用名 = new 外部类名.内部类名();
 *3.局部内部类:
 *3.1也可以直接访问外部类的属性
 *3.2也可以通过 外部类名.this  访问外部类当前对象
 *3.3局部内部类只能在方法内部被访问,修饰符只能是默认的
 *4.匿名内部类:在需要一个类的具体子类实例的时候,临时的生成一个类使用
 *new 类名(){
 * 重写方法;
 *};
 *4.1匿名内部类访问外部方法的属性,该属性会被转换为常量
 *4.2匿名内部类中新增的属性和方法,只能在匿名内部类内部使用
 *
 */
 public static void main(String[] args)
 {
  Person per = new Person("老陈",18);
  Person.Computer pc = per.new Computer("外星人");
  Person.Computer pc1 = new Person("简自豪",18).new Computer("外星人");
  pc.runGame();
  pc1.runGame();
  Person.Computer1 pc11 = new Person.Computer1("网吧的电脑");
  pc11.runGame();
  per.useComputer();
  String str = "啦啦啦";
  //str = "罗库偶偶";
  Computer com = new Computer(){
   @Override
   public void runGame()
   {
    // TODO Auto-generated method stub
    System.out.println(per.age+"岁的"+per.name+"在玩啦啦啦啦啦德玛西塔");
    System.out.println(str);
   }
   
  };
  com.runGame();
  //具体类的匿名内部类独享
  /*Toy toy = new Toy(){
   @Override
   public void jump()
   {
    System.out.println("跳出地球");
   }
  };*/
  toy.jump();
  toy.jump();
  //toy.go();
  //System.out.println(toy.);
 }
}

 class Person {
 String name;
 int age;
 static int age1 = 18;
 static String name1 = "全职高手";
 public Person(String name,int age)
 {
  super();
  this.name = name;
  this.age = age;
 }
 public void playGame(){
  System.out.println(name+"玩游戏");
 }
 public class Computer{
  String name;
  public Computer(String name)
  {
   super();
   this.name = name;
  }
  public void runGame(){
   System.out.println(name+"运行游戏");
   System.out.println(age+"岁的"+Person.this.name+"玩游戏");
  }
 }
 public static class Computer1{
  String name;
  public Computer1(String name)
  {
   super();
   this.name = name;
  }
  public void runGame(){
   System.out.println(name+"运行游戏");
   System.out.println(Person.age1+"的"+Person.name1+"在玩游戏");
  }
 }
 public void useComputer(){
   class Computer{
   String name;
   public Computer(String name)
   {
    super();
    this.name = name;
   }
   public void runGame(){
    System.out.println(name+"运行游戏");
    System.out.println(Person.this.age+"的"+Person.this.name+"正在玩游戏");
   }
  }
  Computer com = new Computer("笔记本");
  com.runGame();
 }
}

public interface Computer {
 void runGame();
}

public class Toy {
 public void jump(){
  System.out.println("玩具跳一下");
 }
}
更多java知识请访问:How2J 的 Java教程

原创粉丝点击