Java的访问控制

Java有四种访问控制:public、、protected、default、private。

项目结构

定义Car父类

package com.sea;

public class Car {
	
	protected String name;
	String color;
	
	public Car(String name){
		this.name = name;
	}
	
}

定义Ferrari子类

子类和父类在同一个包中(com.sea),子类可以访问从父类继承的protected属性、default属性。

package com.sea;

public class Ferrari extends Car {

	public Ferrari(String name) {
		super(name);
	}
	
	public String getName(){
		return this.name;
	}
	
	public String getColor(){
		return this.color;
	}
	
}

  

定义BMW子类

子类和父类不在同一个包中(com.sea),子类可以访问从父类继承的protected属性,不能访问从父类继承的default属性。

package com.lake;

import com.sea.Car;


public class BMW extends Car {

	public BMW(String name) {
		super(name);
	}

	public String getName(){
		return this.name;
	}
	
	public String getColor(){
		return this.color; // 编译报错:the field Car.color is not visible
	}
		
}

改进后的BMW子类

Java的访问控制只对编译阶段有效,运行阶段可通过反射访问任何包中的任何类的任何成员。

package com.lake;
 
import java.lang.reflect.Field;

import com.sea.Car;
 
 
public class BMW extends Car {
 
    public BMW(String name) {
        super(name);
    }
 
    public String getName(){
        return this.name;
    }
     
    public String getColor() throws Exception{
       Class<?> clazz = this.getClass().getSuperclass();
       Field field = clazz.getDeclaredField("color");
       field.setAccessible(true);
       Object obj = field.get(this);
       return (String)obj;
    }
         
}

Test类

 

package com.test;

import com.lake.BMW;

public class Test {

    public static void main(String[] args) throws Exception {
        BMW bmw = new BMW("750Li");
        System.out.println(bmw.getColor());
    }

}

运行结果

红色

 

posted on 2017-06-09 15:20  沙滩海风  阅读(164)  评论(0编辑  收藏  举报

导航