protected的示例代码
时间: 2023-07-02 21:16:00 浏览: 83
以下是一个使用`protected`修饰符的示例代码:
```java
package com.example;
public class Animal {
protected String name;
protected int age;
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
protected void eat() {
System.out.println(name + " is eating");
}
}
package com.example;
public class Dog extends Animal {
private String breed;
public Dog(String name, int age, String breed) {
super(name, age);
this.breed = breed;
}
public void bark() {
System.out.println(name + " is barking");
}
public void eatFood() {
eat();
}
}
package com.example;
public class Main {
public static void main(String[] args) {
Dog dog = new Dog("Buddy", 3, "Labrador");
dog.bark(); // 输出:Buddy is barking
dog.eatFood(); // 输出:Buddy is eating
}
}
```
在上面的示例代码中,`Animal`类中的`name`、`age`和`eat()`方法都使用了`protected`修饰符,因此它们可以被`Dog`类继承并访问。`Dog`类中的`bark()`方法和`eatFood()`方法都可以访问`Animal`类中的`name`和`eat()`方法。在`Main`类中,我们创建了`Dog`类的实例,并调用了`bark()`方法和`eatFood()`方法,输出了相应的结果。
阅读全文