首页 > 代码库 > 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内部类
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。