在Java中,子类可以通过重写(Override)父类的方法来实现多态。要重写父类的方法,需要遵循以下规则:
public,则子类方法也必须是public。下面是一个简单的例子,演示了如何在Java中重写父类的方法:
// 父类
class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
}
// 子类
class Dog extends Animal {
// 重写父类的makeSound方法
@Override
public void makeSound() {
System.out.println("The dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
animal.makeSound(); // 输出 "The animal makes a sound"
Dog dog = new Dog();
dog.makeSound(); // 输出 "The dog barks"
Animal dogAsAnimal = new Dog();
dogAsAnimal.makeSound(); // 输出 "The dog barks",因为Dog类重写了makeSound方法
}
}
在这个例子中,Dog类继承了Animal类,并重写了makeSound方法。当我们使用Dog对象调用makeSound方法时,将执行Dog类中定义的方法,而不是Animal类中的方法。这就是多态的体现。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。