Usage of class,public in Java
A Java Access Omphalos (Access specifiers)
Java has public, protect, friendly, private four access rights, and these four access permissions are getting smaller.
1. Friendly
1) If the data member or method within a class does not have any permissions omphalos, then its default access is friendly. All other classes within the same package can access friendly members, but the classes outside the package is private.
2) for Classes,java that do not use the package in the same folder, these classes will be automatically named as the default package that is subordinate to the directory, and can call friendly members of class in each other. The following two classes are in two files in the same folder, although the package is not introduced, but is subordinate to the same default.
Class sundae{
The following two methods default to Friendly
Sundae () {}
Void f () {System.out.println ("sundae.f ()");
}
public class icecream{
public static void Main (string[] args) {
Sundae x = new Sundae ();
X.F ();
}
}
2. Public: can be called by any class
3. Private:private members can only be called within the class to which the member belongs, such as:
Class sundae{
Private Sundae () {}//can only be called in Sundae class
Sundae (int i) {}
Static Sundae Makasundae () {
return new Sundae ();
}
}
public class icecream{
public static void Main (string[] args) {
The constructor sundae () in Sundae class is private,
So it can't be initialized with it.
Sundae x = new Sundae ();
Sundae y = new Sundae (1),//sundae (int) is friendly, where you can call
Sundae Z = Sundae.makasundae ();
}
}
4. Protected: With friendly access, it can be accessed by subclass (including descendant classes, subclasses of subclasses, of course). That is, it can be accessed both by the classes in the same package and by the subclass of the protected member's class.
Two class's access rights
1. Class also has public, protect, friendly, private four access permissions:
1) Public: can be used anywhere
2) Protect, Private: In addition to its own, no class can be used, so class cannot be
Protected or private (except inner class)
3) Friendly: Classes can be used in the same package
2. How to call the class that the constructor is declared as private
1) Use the static function
2) Use Singteton mode
Class soup{
Private Soup () {}
(1) Static function method
public static Soup Makesout () {
return new Soup ();
}
(2) The "Singleton" pattern:
private static Soup PS1 = new Soup ();
public static Soup access () {
return PS1;
}
public void F (String msg) {
System.out.println ("F (" + msg + ")");
}
}
public class lunch{
public static void Main (string[] args) {
Soup priv1 = new Soup (); Compile error
Soup priv2 = Soup.makesout ();
Soup Priv3 = soup.access ();
PRIV2.F ("Priv2");
PRIV3.F ("Priv3");
}
Http://blog.sina.com.cn/s/blog_45ce6045010187ks.html
Usage of class,public in Java