//创建内外类
public class createinner191 {
public static void main(String []args)
{
outclass o=new outclass();
o.ship("我爱你");
outclass o1=new outclass();
outclass.inner1 i1=o1.showinner1();//生成内部类对象可以通过外部类里的方法返回一个new 内部类对象,然后再生成一个引用即可
System.out.println(i1.getinner1());
outclass.inner2 i2=o1.showinner2("我喜欢你");
System.out.println(i2.getinner2());
outclass o2=new outclass();
outclass.inner1 ii1=o2.new inner1();//这里生成内部类对象,运用了.new (等号右边)用法是 外部类对象.new 内部类对象
System.out.println(ii1.getinner1());
}
}
class outclass
{
class inner1
{
private int x=1;
inner1()
{
System.out.println("inner1");
}
public int getinner1()
{
return x;
}
}
class inner2
{
String s;
inner2(String s)
{
this.s=s;
System.out.println("inner2");
}
String getinner2()
{
return s;
}
}
inner1 showinner1() //用于生成内部类对象
{
return new inner1();
}
inner2 showinner2(String s) //用于生成内部类对象
{
return new inner2(s);
}
public void ship(String s)
{
inner1 i1=new inner1();//在外部类方法里边,可以直接生成内部类对象
inner2 i2=new inner2(s);
System.out.println(i1.getinner1());
System.out.println(i2.getinner2());
}
}
创建内部类
最新推荐文章于 2024-05-16 20:30:57 发布