JAVA中的权限修饰符

JAVA中权限修饰符有四类:private,默认,protected,public

权限修饰符同一个类中同一个包中不同包下的子类不同包
private
默认
protected
public

protected权限修饰符的注意事项:

  1. 在子类中可以通过子类对象来访问父类的protected属性和方法
  2. 在子类中不能通过父类对象来访问父类的protected属性和方法
  3. 在子类中不能通过其他子类的对象来访问父类的protected属性和方法

举例

public class Main {
    //私有方法:只能在本类中使用,若该类被继承,该方法不会被继承
    private void privateMethod(){
        System.out.println("private方法");
    }

    //默认方法: 只能在该包中进行访问
    void method(){
        System.out.println("默认方法");
    }
    //protected修饰的方法: 同包和父子类中能进行访问
    protected void protectedMethod(){
        System.out.println("protected方法");
    }

    //public修饰的方法: 同包,不同包都能进行访问
    public void publicMethod(){
        System.out.println("public方法");
    }
    
    public static void main(String[] args) {
        Main main=new Main();
        main.privateMethod();
        main.method();
        main.protectedMethod();
        main.publicMethod();
    }
}

运行结果

private方法
默认方法
protected方法
public方法

定义一个学生类进行测试

package father;

public class Student {
    public int id;

    protected String name;

    double score;

    private int age;

    public Student(int id, String name, double score, int age) {
        this.id = id;
        this.name = name;
        this.score = score;
        this.age = age;
    }

    public Student() {
    }
}

在同一包下测试

package father;
public class TestStudent1 {
    public static void main(String[] args) {
        Student student = new Student(1,"学生1",100.0,18);
        //public
        System.out.println(student.id);
        //protected
        System.out.println(student.name);
        //默认
        System.out.println(student.score);
        //private 编译失败,说明即使相同包,private修饰的变量也不能在其他类中访问
        System.out.println(student.age);
    }
}

在不同包下测试

package son;

import father.Student;

public class TestStudent2 {
    public static void main(String[] args) {
        Student student = new Student(2,"学生2",97.0,18);
        //public 可以正常访问
        System.out.println(student.id);
        //protected 编译失败
        System.out.println(student.name);
        //default 编译失败
        System.out.println(student.score);
        //private 编译失败
        System.out.println(student.age); 
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值