In Java, when an object of an inner class is generated, the object is kept in contact with the external class that made it, so that the inner class object can access all members of its external class object, including private members.
This internal class object is not particularly supported for access to objects of other classes, in accordance with the syntax of general access rights. What you need to explore here is how external classes and other class objects can access an inner class object, the visibility problem of an inner class.
The following is an example program, Out.java, that contains 4 internal classes (Private,default,protected,public) with different access rights, and in each inner class, contains 4 members and methods with different access rights. A method for obtaining an internal class instance is provided in the external class out.
Out.java
package com.zj.main;
public class Out {
public Privatein Getprivatein () {
return new Privatein ();
}
public Defaultin Getdefaultin () {
return new Defaultin ();
}
public Protectedin Getprotectedin () {
return new Protectedin ();
}
public publicin getpublicin () {
return new Publicin ();
}
Private class Privatein implements inmethod{
private int private_arg;
int default_arg;
protected int protected_arg;
public int public_arg;
private void Private_method () {};
void Default_method () {};
protected void Protected_method () {};
public void Public_method () {};
}
class Defaultin implements inmethod{
private int private_arg;
int default_arg;
protected int protected_arg;
public int public_arg;
private void Private_method () {};
void Default_method () {};
protected void Protected_method () {};
public void Public_method () {};
}
protected class Protectedin implements inmethod{
private int private_arg;
int default_arg;
protected int protected_arg;
public int public_arg;
private void Private_method () {};
void Default_method () {};
protected void Protected_method () {};
public void Public_method () {};
}
public class Publicin implements inmethod{
private int private_arg;
int default_arg;
protected int protected_arg;
public int public_arg;
private void Private_method () {};
void Default_method () {};
protected void Protected_method () {};
public void Public_method () {};
}
public static void Main (string[] args) {
//create an outer object
out out=new out ();
//create a private inner object by ' new '
Out.privatein privatein=out.new Privatein ();
privatein.private_arg=0;
Privatein.private_method ();
//Create a private inner object by ' out ' of ' s method '
Out.privatein privateIn2 = Out.getprivatein ();
privatein2.private_arg = 0;
Privatein2.private_method ();
}
}