class Outter
{
String name="outter";
String oname="oname";
public class Innter
{
String name="inner";
String iname="iname";
}
}
public class testb
{
public static void main ( String args[] ) {
Outter o1 = new Outter();
System.out.println(o1.oname);
//System.out.println(o1.Innter.iname); fails because Innter don't have instance
//Innter i1 = new Innter(); fails because this is a inner class
//Innter i1 = new Outter.Inner(); fails because Inner is not a member.
Outter.Innter i1 = o1.new Innter();
System.out.println(i1.iname);
}
}
---------- java ----------
oname
iname
==Advantage: Inner class can access Outter class menber
class Outter
{
String name="outter";
String oname="oname";
public class Innter
{
String name="inner";
String iname="iname";
public String getInfo() {
return "oname from Innter = " + oname;
}
}
// correct usage
public String getInfo() {
Innter i1 = new Innter();
return i1.name + "\n" + i1.getInfo();
}
/* incorrect usage because no Inner instance
public String getInfo() {
return Innter.name;
}
*/
}
public class testb
{
public static void main ( String args[] ) {
Outter o1 = new Outter();
System.out.println(o1.getInfo());
}
}
---------- java ----------
inner
oname from Innter = oname
==Static inner class and access
class Outter
{
String name="outter";
String oname="oname";
public static class Innter
{
static String name="inner";
static String iname="iname";
}
// correct usage
public String getInfo() {
return Innter.name; //access type 1
}
}
public class testb
{
public static void main ( String args[] ) {
Outter o1 = new Outter();
System.out.println(o1.getInfo());
System.out.println(Outter.Innter.name); //access type2
// System.out.println(o1.Inter.name); failure Inter is not a class member.
}
}
没有评论:
发表评论