Java的面向对象

08-四种权限修饰符

2021-07-01 740 0

简介 四种权限修饰符的使用以及导致的可见性

四种权限描述符的使用


upfile

    1. 类内部, private 可见

    2. 同一个包,default可见

    3. 不同包的子类中, protected可见

    4. 同一个工程, public可见

    1和4 用的最对, 另外的两个用的比较少



    1. 类内部, private 可见

//Fruits.java
package com.ylaihui.oop4;

public class Fruits {
    	private String name;
    	int id;
    	protected String color;
    	public double price;
	
	private void methodPrivate(){ }
	void methodDefault(){}
	protected void methodProtected(){}
	public void methodPublic(){}
	void fun(){
		this.name = "apple";
		this.methodPrivate();
	}
}

2. 同一个包,default可见

//FruitsTest.java
package com.ylaihui.oop4;

public class FruitsTest {
    	public static void main(String[] args) {
    		Fruits fruits = new Fruits();
    		fruits.color = "red";
    		fruits.id = 1001;
    		fruits.price = 11.11;
		
		fruits.methodDefault();
		fruits.methodProtected();
		fruits.methodPublic();
		
		//  is not visible
//		fruits.name = "apple";
//		fruits.methodPrivate();
	}
}

3. 不同包的子类中, protected可见

//Apple.java
package com.ylaihui.oop5;

import com.ylaihui.oop4.Fruits;

public class Apple extends Fruits{
    	public void fun(){
    		color = "red";
    		price = 11.22;
        methodProtected();	
        methodPublic();
		
		//  is not visible
//		name = "red apple";
//		id = 1001;
//		methodPrivate();
//		methodDefault();
	}
}

4. 同一个工程, public可见

//AppleTest.java
package com.ylaihui.oop5;

public class AppleTest {
    	public static void main(String[] args) {
    		Apple ap = new Apple();
    		
    		ap.price = 12.11;
    		ap.methodPublic();
		
		// is not visible
//		ap.name = "red apple";
//		ap.id = 1001;
//		ap.color = "red";
		
		// is not visible
//		ap.methodPrivate();
//		ap.methodDefault();
//		ap.methodProtected();
		
	}
}


点赞 0

文章评论

欢迎您:

纸上得来终觉浅,绝知此事要躬行!

112 文章 57749 浏览 3 评论

联系我

  •   QQ:    361352119
  •  Email:  lisimmy@sina.com
  • 微信: