java private,protected,default,public 的区别


这些英文版的文章,以前写的,现在翻译成中文。希望对大家有帮助
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();
	}

}
如果你是一名技术人员可加我QQ 2651-0442-02,如果你是java技术人还可以加入QQ群 1784-9136-0
你将得到的不仅仅是技术的交流,还有职业机会,人生解惑.
首发地址:月小升博客https://java-er.com/blog/java-private-protected-default-public/
无特殊说明,文章均为月小升原创,欢迎转载,转载请注明本文地址,谢谢
此条目发表在 JAVA 分类目录,贴了 标签。将固定链接加入收藏夹。
既然来了,就评论一下,不会怀孕的

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">