protected访问权限修饰符
在一个包中访问另一个包下的类体中由protected修饰的成员,流程如下:
- 导包(anotherpackage)。注意另一个类(Person)必须为public,否则无法跨包访问该类
- 创建子类(Kid)继承(Person),重写方法(eat())
- 在main中创建子类对象,调用方法(eat())
package com.cskaoyan.ex.anotherpackage;
public class Person {
protected void eat(){
System.out.println("eat food");
}
}
package com.cskaoyan.ex.onepackage;
import com.cskaoyan.ex.anotherpackage.Person;
public class DemoProtected {
public static void main(String[] args) {
// 创建子类对象
Kid kid = new Kid();
// 调用子类eat()方法
kid.eat();
}
}
class Kid extends Person{
/**
* 在子类的普通方法中也无法直接调用父类中protected修饰的方法
*/
public void test(){
Person person = new Person();
// 报错 eat() has protected access
// person.eat();
}
/**
* 在子类的重写方法中可以直接调用父类中protected修饰的方法
*/
@Override
protected void eat() {
//继承子父类的方法
super.eat();
System.out.println("eat Children's meal");
}
}
经典案例
Object类中的有被protected修饰的Clone方法,如果想要实现一个类的Clone就要调用该方法
package com.cskaoyan.ex;
/**
* 创建子类对象,调用重写的Clone方法
*/
public class DemoClone {
public static void main(String[] args) {
Student student = new Student();
Student studentClone=null;
try {
//克隆了一个Student对象
studentClone=student.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
/**
* Student类实现Cloneable功能接口,默认继承Object类,重写Object类中的Clone方法
*/
class Student implements Cloneable{
//重写Cloneable
@Override
public Student clone() throws CloneNotSupportedException{
return (Student)super.clone();
}
}