首页 > 代码库 > java内部类

java内部类

1.静态嵌套类

package com.wangfeng;import java.util.ArrayList;public class Outer {    public static class Inner{        private String name;        public Inner(String name){            this.name = name;        }        public String getName() {            return name;        }        public void setName(String name) {            this.name = name;        }            }        public boolean addMembers(Inner member){        this.members.add(member);        return true;    }        public void printMembers(){        for(Inner member:this.members){            System.out.println(member.getName());        }    }        private ArrayList<Inner> members = new ArrayList<>();    public ArrayList<Inner> getMembers() {        return members;    }    public void setMembers(ArrayList<Inner> members) {        this.members = members;    }}

主要就是内部类前面有static

如果这样的类在外部可见可以初始化的方式为:

Outer.Inner in = new Outer.Inner("wangfeng2");

2.内部类

import java.util.ArrayList;public class Outer {	public class Inner{		private String name;		public Inner(String name){			this.name = name;		}		public String getName() {			return name;		}		public void setName(String name) {			this.name = name;		}			}		public boolean addMembers(Inner member){		this.members.add(member);		return true;	}		public void printMembers(){		for(Inner member:this.members){			System.out.println(member.getName());		}	}		private ArrayList<Inner> members = new ArrayList<>();	public ArrayList<Inner> getMembers() {		return members;	}	public void setMembers(ArrayList<Inner> members) {		this.members = members;	}}

 

主要就是内部类前面没有static

如果这样的类在外部可见可以初始化的方式为:

Outer.Inner in = out.new Inner("wangfeng2");

3.局部内部类(即定义在方法里面的类)

public interface People {	String getName();	void setName(String name);}

  

 

public class Hello {	public static void main(String[] args){		People p = PeopleFactory();		p.setName("adfasd");		System.out.println(p.getName());	}		public static People PeopleFactory(){		class Man implements People{			String name;			public String getName(){				return name;			}			public void setName(String name){				this.name = name;			}		}		return new Man();	}}

 

 

4.匿名内部类

 

public class Hello {	public static void main(String[] args){		People p = PeopleFactoryAnonymous();		p.setName("adfasd");		System.out.println(p.getName());	}		public static People PeopleFactory(){		class Man implements People{			String name;			public String getName(){				return name;			}			public void setName(String name){				this.name = name;			}		}		return new Man();	}		public static People PeopleFactoryAnonymous(){		return new People(){			String name;			public String getName(){				return name;			}			public void setName(String name){				this.name = name;			}		};	}}

  

 

 

 

java内部类