Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5707858
  • 博文数量: 409
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 8273
  • 用 户 组: 普通用户
  • 注册时间: 2013-10-23 19:15
个人简介

qq:78080458 学习交流群:150633458

文章分类

全部博文(409)

文章存档

2019年(127)

2018年(130)

2016年(20)

2015年(60)

2014年(41)

2013年(31)

分类: Java

2013-10-25 18:05:15

内部类:在类的内部定义另一个类,方便访问外部类的所有的成员。内部类可以嵌套,但是如果定义在方法之内,那么他的作用域就在方法中,出了方法就不能使用了。必须先产生外部类对象,然后产生内部类对象
class out
{
    private int index = 100;
    class in
    {
        private int index = 50;
        void print()
        {
            int index = 30;
            System.out.println(index);               //30,print访问的是局部变量
           System.out.println(this.index);          //50
           System.out.println(out.this.index);    //100
        }
     }

    in getIn()
    {
        return new in();
    }
}

class init
{
    public static void main(String[] args)
    {
        out o = new out();
//        o.in i = out.getIn();
//        i.print();

        o.in i = o.new in();    //内部类要访问外部类,那么必须有关联性,不能直接new
    }
}
当在方法中定义一个类,那么如果类要访问方法的变量,那么这个变量必须为final。内部类的修饰符public,protected,private,abstract,static,  非静态的内部类不能有静态方法,只有顶层类才可以有static成员

内部类实现接口,更好的管理类
interfice Animal
{
    void eat();
    void sleep();
}
class Zoo
{
    private class Tiger implements Animal
    {
        public void eat
            {
                  System.put.println("tiger eat");
             }
        public void sleep()
        {
            System.put.println("tiger sleep");

        }
    }
    Animal getAnimal()
    {
        return new Tiger();
    }
}

class Test
{
    public static void main(String[] args)
    {
        Zoo z = new Zoo();
        Animal an = z.getAnimal();
        an.eat();            //利用内部类的接口访问私有成员
        an.sleep();
}
}



内部类和接口的函数名相同,但意义不一样

interface Machine
{
 void run();
}

class Person
{
 void run()
 {
  System.out.println("person run");
 }
}

class Robot extends Person
{
 private class MachineHeart implements Machine
 {
  public void run()
  {
   System.out.println("robot heart");
  }
 }
 
 Machine getMachine()
 {
  return new MachineHerat();
 }
}

class Test
{
 public void main(String[] args)
 {
  Robot robot = new Robot();
  Machine m = robot.getMachine();
  m.run();
  robot.run();
 }
}


内部类解决c++中多继承问题

class A
{
 void f1();
}

abstract B
{
 abstract void f2();
}

class C extends A
{
 B getB()
 {
  return new B()            //返回一个内置类
  {
   public void f2()
   {}
  };
 }
}

class Test
{
 static void m1(A a)
 {
  a.f1();
 }
 
 static void m2(B b)
 {
  b.f2();
 }
 
 public static void main(String[] args)
 {
  C c = new C();
  m1(c);
  m2(c.getB());
 }
}

阅读(12667) | 评论(0) | 转发(2) |
给主人留下些什么吧!~~