Java protected 关键字

  • 定义和用法

    protected关键字是用于属性,方法和构造函数的访问修饰符,使他们在同一个包和子类访问。
  • 示例

    Student子类访问Person与类protected属性:
    class Person {
      protected String fname = "John";
      protected String lname = "Doe";
      protected String email = "john@doe.com";
      protected int age = 24;
    }
    
    class Student extends Person {
      private int graduationYear = 2018;
      public static void main(String[] args) {
        Student myObj = new Student();
        System.out.println("Name: " + myObj.fname + " " + myObj.lname);
        System.out.println("Email: " + myObj.email);
        System.out.println("Age: " + myObj.age);
        System.out.println("Graduation Year: " + myObj.graduationYear);
      }
    }
    
    尝试一下
  • 相关页面

    Java 教程:Java 修饰符