内部类的作用?1、抽象类中包含一个内部接口如何实现与调用 ;2、接口中包含一个内部抽象类如何调用

内部类作用:

1、可以直接调用外部类的私有成员变量

package com.swift;

public class Neibulei 
{
    public static void main(String[] args) 
    {
        new Outer("swift").getprint();
    }
}
class Outer
{
    private String name;
    public Outer(String name)
    {
        this.name=name;
    }
    public void getprint()
    {
        new Inner().print();
    }
    class Inner
    {
        public void print()
        {
            System.out.println("The name is "+name);
        }
    }
}

否则,如果内部类在外边则需要进行复杂的参数传递

参数传递法如下:

package com.swift;

public class Neibulei2 
{
    public static void main(String[] args) 
    {
        Outer2 o2=new Outer2("swift");
        o2.getprint(o2);
    }
}
class Outer2
{
    private String name;
    public Outer2(String name)
    {
        this.name=name;
    }
    public void getprint(Outer2 o2)
    {
        new Inner2().print(o2);
    }
    public String getName()
    {
        return this.name;
    }
    
}
class Inner2
    {
        public void print(Outer2 o2)
        {
            System.out.println("The name is "+o2.getName());
        }
    }

或者也可以用构造方法通过this关键字传递

package com.swift;

class Neibulei3 
{
    public static void main(String[] args) 
    {
        new Outer3("swift").getprint();
    }
}
class Outer3
{
    private String name;
    public Outer3(String name)
    {
        this.name=name;
        
    }
    public void getprint()
    {
        new Inner3(this).print();
    }
    public String getName()
    {
        return this.name;
    }
    
}
class Inner3
    {
        private Outer3 outer;
        public Inner3(Outer3 outer)
        {
            this.outer=outer;
        }
        public void print()
        {
            System.out.println("The name is "+outer.getName());
        }
    }

也可以这样写

package com.swift;

public class Neibulei4
{
    public static void main(String[] args) 
    {
        
        Outer4.Inner4 in= new Outer4().new Inner4();
        in.print();
    }
}
class Outer4
{
    private String name="swift";
    
           class Inner4
           {
        public void print()
           {
            System.out.println("The name is "+name);
           }
        }


}

所以一个篇代码也可以改写成如下

new Outer("swift").new Inner().print();

或者

Outer.Inner in=new Outer("swift").new Inner();
in.print();

同时内部也可以放在外部类的方法当中

package com.swift;

public class Neibu {
    public static void main(String[] args) {
        new Out().fun(100);
    }
}
class Out {
    private String name = "swift";
    public void fun(int temp) {
        class In {
            public void print() {
                System.out.println("temp =" + temp);
                System.out.println("the name is " + name);
            }
        }
        new In().print();
    }
}

 

1、抽象类中包含一个内部接口如何实现与调用

 


 

2、接口中包含一个内部抽象类如何调用

 

posted @ 2017-10-29 21:54  Advancing-Swift  阅读(541)  评论(0编辑  收藏  举报