【面向对象基础】——protected访问权限修饰符

protected访问权限修饰符

在一个包中访问另一个包下的类体中由protected修饰的成员,流程如下:

  1. 导包(anotherpackage)。注意另一个类(Person)必须为public,否则无法跨包访问该类
  2. 创建子类(Kid)继承(Person),重写方法(eat())
  3. 在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();
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值