Java 访问修饰符示例:Mammal 和 Cat 类
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 中访问修饰符的作用,以及它们如何影响类成员的访问权限。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/pa1n 著作权归作者所有。请勿转载和采集!