这些英文版的文章,以前写的,现在翻译成中文。希望对大家有帮助
Java Access Modifiers
1. private
2. protected
3. default
4. public
1.private.
if a method is private , you only use it in it's self class
如果方法为pricate,只能在自己的class里使用
2.default.
if a metod is default.you can use it in the class who is in the same package
你可以在相同的package下的类里使用default
3.protected.
if a metod is protectd.you can use it in the class who is in the same package and in his subclass
可以在相同的package下的自己的子类里使用
4.public
if a metod is public.you can use it anywhere.
任何地方都可以用
关系矩阵
Modifier | Class | Package | Subclass | World
public | Y | Y | Y | Y
protected | Y | Y | Y | N
no modifier | Y | Y | N | N
private | Y | N | N | N
/**
java-er.com
learn java is so easy
*/
package com.javaer.examples;
public class Accessmodifiers {
private void run(){
System.out.println("I am running");
}
public void stop(){
System.out.println("I am stopping");
}
protected void sleep(){
System.out.println("I am sleeping");
}
void eat(){
System.out.println("I am eating");
}
/**
* @param args
*/
public static void main(String[] args) {
//there,you can use all the method in the class Accessmodifiers
Accessmodifiers am = new Accessmodifiers();
am.run();
am.stop();
am.sleep();
am.eat();
AccessmodifiersA ama = new AccessmodifiersA();
ama.test();
}
}
//AccessmodifiersA is a subclass of Accessmodifiers
class AccessmodifiersA{
public void test(){
Accessmodifiers am = new Accessmodifiers();
//am.run();
am.sleep();
am.stop();
//am.eat();
}
}
/**
java-er.com
learn java is so easy
*/
package com.javaer.examples;
public class Accessmodifiers2 {
/**
* @param args
*/
public static void main(String[] args) {
//there,you can use all the method in the class Accessmodifiers except priavte method run.
Accessmodifiers am = new Accessmodifiers();
//am.run();
am.stop();
am.sleep();
am.eat();
}
}
package com.javaer.examples2; // note:package is changed import com.javaer.examples.Accessmodifiers; public class Accessmodifiers3 { /** * @param args */ public static void main(String[] args) { //there,you can only use the public method in the class Accessmodifiers. Accessmodifiers am = new Accessmodifiers(); //am.run(); am.stop(); //am.sleep(); //am.eat(); } }