在Java中,子类可以通过重写(Override)父类的方法来实现多态。重写意味着子类提供了一个与父类中具有相同名称、参数类型和返回类型的新实现。以下是如何在Java中重写父类方法的步骤:
public class Parent {
public void display() {
System.out.println("This is the Parent class method.");
}
}
public class Child extends Parent {
// ...
}
public class Child extends Parent {
@Override
public void display() {
System.out.println("This is the Child class method.");
}
}
这里,我们使用了@Override注解,它是一个可选的注解,用于指示我们打算重写父类的方法。这有助于编译器检查我们是否正确地重写了方法,以及是否满足了重写的要求(例如,方法签名必须与父类中的方法相同)。
public class Main {
public static void main(String[] args) {
Parent parent = new Parent();
parent.display(); // 输出:This is the Parent class method.
Child child = new Child();
child.display(); // 输出:This is the Child class method.
// 使用父类引用指向子类对象
Parent parentWithChild = new Child();
parentWithChild.display(); // 输出:This is the Child class method.
}
}
在这个例子中,我们可以看到,当我们使用子类对象调用display()方法时,将执行子类中重写的方法。此外,当我们使用父类引用指向子类对象时,仍然会执行子类中重写的方法。这是因为Java中的方法调用是基于对象的实际类型,而不是引用类型。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。