public class Mammal {
    public double weight;
    protected double height;
    double legs;
    private double tail;

    public void printWeight() {
        System.out.println('The weight is: ' + weight);
    }

    protected void printHeight() {
        System.out.println('The height is: ' + height);
    }

    void printLegs() {
        System.out.println('The number of legs is: ' + legs);
    }

    private void printTail() {
        System.out.println('The length of tail is: ' + tail);
    }
}
public class Cat extends Mammal {
    @Override
    public void printWeight() {
        System.out.println('The weight of the cat is: ' + weight);
    }
}
public class Test {
    public static void main(String[] args) {
        Mammal animal = new Mammal();
        animal.weight = 10.5;
        animal.height = 25.0;
        animal.legs = 4;
        // animal.tail = 15.0; // Error: 'tail' has private access in 'Mammal'
        animal.printWeight(); // The weight is: 10.5
        animal.printHeight(); // The height is: 25.0
        animal.printLegs(); // The number of legs is: 4
        // animal.printTail(); // Error: 'printTail()' has private access in 'Mammal'

        Cat tommy = new Cat();
        tommy.weight = 8.0;
        tommy.height = 20.0;
        tommy.legs = 4;
        // tommy.tail = 12.0; // Error: 'tail' has private access in 'Mammal'
        tommy.printWeight(); // The weight of the cat is: 8.0
        tommy.printHeight(); // The height is: 20.0
        tommy.printLegs(); // The number of legs is: 4
        // tommy.printTail(); // Error: 'printTail()' has private access in 'Mammal'

        animal = tommy;
        animal.printWeight(); // The weight of the cat is: 8.0
    }
}

代码解析

该代码演示了 Java 中的访问修饰符 (public, protected, private) 如何影响类成员的访问权限。

  • Mammal 类

    • 定义了四个实例变量:weight、height、legs 和 tail。
    • weight 和 height 使用了 public 和 protected 访问修饰符,可以被其他类访问。
    • legs 使用了默认访问修饰符,只能被同一包内的类访问。
    • tail 使用了 private 访问修饰符,只能在 Mammal 类内部访问。
    • 定义了四个实例方法:printWeight、printHeight、printLegs 和 printTail。
    • 访问修饰符与实例变量的规则相同。
  • Cat 类

    • 是 Mammal 类的子类,继承了 Mammal 类的所有实例变量和实例方法。
    • 重写了 printWeight 方法,以输出猫的重量。
  • Test 类

    • 包含了主方法,用于测试 Mammal 类和 Cat 类的实例。
    • 在主方法中,首先创建了一个 Mammal 类的实例 animal,并给其实例变量赋值。
    • 然后调用 animal 的实例方法打印出 weight、height 和 legs 的值。
    • 接着创建了一个 Cat 类的实例 tommy,并给其实例变量赋值。
    • 再次调用 tommy 的实例方法打印出 weight、height 和 legs 的值。
    • 然后将 tommy 赋值给 animal,再次调用 animal 的实例方法打印出 weight 的值。

通过该代码示例,可以清晰地理解 Java 中访问修饰符的作用,以及它们如何影响类成员的访问权限。

Java 访问修饰符示例:Mammal 和 Cat 类