四种权限修饰符的测试

四种权限修饰符的测试

  • A:案例演示
    • 四种权限修饰符
  • B:结论

              本类     同一个包下(子类和无关类)  不同包下(子类)    不同包下(无关类)
    private     Y       
    默认        Y       Y
    protected   Y       Y                           Y
    public      Y       Y                           Y               Y
    

protected测试1:不同包下(无关类)是不能访问的。

package com.baidu;
public class Person {
    private String name;
    private int age;
    public Person(){}

    public Person(String name, int age){
        this.name = name;
        this.age = age;
    }

    public void setNage(String name){
        this.name = name;
    }

    public String getName(){
        return name;
    }

    public void setAge(int age){
        this.age = age;
    }

    public int getAge(){
        return age;
    }

    protected void print(){
        System.out.println("print");
    }
}

package com.heima;
import com.baidu.Person;
import java.util.Scanner;
class Demo01_Package {
    public static void main(String[] args) {
        Person p = new Person("张三",23);
        System.out.println(p.getName() + "..." + p.getAge());
        //在不同包下的无关类是不允许访问,因为是protected修饰的
        p.print();
    }
}

result

protected测试2:被protected修饰,在不同包下(子类)是可以访问的。

package com.baidu;
public class Person {
    private String name;
    private int age;
    public Person(){}

    public Person(String name, int age){
        this.name = name;
        this.age = age;
    }

    public void setNage(String name){
        this.name = name;
    }

    public String getName(){
        return name;
    }

    public void setAge(int age){
        this.age = age;
    }

    public int getAge(){
        return age;
    }

    protected void print(){
        System.out.println("print");
    }
}

package com.xxx;
import com.baidu.Person;
public class Student extends Person {
    public Student(){}

    public Student(String name,int age) {
        super(name,age);
    }

    public void method() {
        print();
    }
}

package com.heima;
import com.xxx.Student;
import java.util.Scanner;
class Demo01_Package {
    public static void main(String[] args) {
        Student stu = new Student("李四",24);
        System.out.println(stu.getName() + "..." + stu.getAge());
        //被protected修饰,在不同包下的子类是允许访问
        stu.method();
    }
}

result

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

左绍骏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值