zoukankan      html  css  js  c++  java
  • Java修饰符public,protected,default,private访问权限

    public

    具有最大的访问权限。所有类可访问。

    protected

    主要是用来保护子类。自身、子类及同一个包中类可以访问

    default

    没有加修饰符的。有时候也称为friendly,它是针对本包访问而设计的。同一包中可以访问。

    private

     访问权限仅限于类的内部,是一种封装的体现。只能被自己访问

      类内部 子类内部(本包) 其他类(本包) 子类内部(外部包) 其他类(外部包)
    public O O O O O
    protected O O O O X
    default O O O X X
    private O X X X X

     

     

     

     

     

    示例代码

    包apkg

    ParentA.java

    package apkg;
    
    public class ParentA {
        public String publicVariable = "public";
        protected String protectedVariable = "protected";
        String variable = "default";
        private String privateVariable = "privater";
        
        public void show() {
            System.out.println(this.publicVariable);
            System.out.println(this.protectedVariable);
            System.out.println(this.variable);
            System.out.println(this.privateVariable);
        }
        
        public static void main(String[] args) {
            ParentA apkg = new ParentA();
            apkg.show();
        }
    }

    SonA.java

    package apkg;
    
    public class SonA extends ParentA {
        public void show() {
            System.out.println(this.publicVariable);
            System.out.println(this.protectedVariable);
            System.out.println(this.variable);
            //System.out.println(this.privateVariable);// 无法访问
        }
    }

    UncleA.java

    package apkg;
    
    import apkg.ParentA;
    
    public class UncleA {
        public void show() {
            ParentA apkg = new ParentA();
            System.out.println(apkg.publicVariable);
            System.out.println(apkg.protectedVariable);
            System.out.println(apkg.variable);
            //System.out.println(apkg.privateVariable);// 无法访问
        }
    }

    包bpkg

    SonB.java

    package bpkg;
    
    import apkg.ParentA;
    
    public class SonB extends ParentA {
        public void show() {
            System.out.println(this.publicVariable);
            System.out.println(this.protectedVariable);
            //System.out.println(this.variable);// 无法访问
            //System.out.println(this.privateVariable);// 无法访问
        }
    }

    UncleB.java

    package bpkg;
    
    import apkg.ParentA;
    
    public class UncleB {
        public void show() {
            ParentA apkg = new ParentA();
            System.out.println(apkg.publicVariable);
            //System.out.println(apkg.protectedVariable);// 无法访问
            //System.out.println(apkg.variable);// 无法访问
            //System.out.println(apkg.privateVariable);// 无法访问
        }
    }

     

     

     

     

     

  • 相关阅读:
    Visio2019专业版激活方法
    I2C总线协议
    latch-up和Antenna-effect
    读--数字集成电路物理设计
    数字IC设计流程与工具
    读--FPGA设计指导原则
    读--数字集成电路设计与实现
    FIFO
    半导体存储器
    触发器
  • 原文地址:https://www.cnblogs.com/yangchongxing/p/8365494.html
Copyright © 2011-2022 走看看