在Java中,override(覆盖)是指在子类中重新定义父类中已存在的方法。覆盖的目的是为了在子类中改变方法的实现方式,以满足子类的特定需求。
要在子类中使用override,需要满足以下几个条件:
-
子类必须继承自父类。
-
子类中的方法名、参数列表和返回类型必须与父类中被覆盖的方法一致。
-
子类中的访问修饰符不能比父类中被覆盖的方法的访问修饰符更严格。例如,如果父类中的方法是public,那么子类中的方法也必须是public。
以下示例演示了如何在Java中使用override:
// 父类 class Parent { public void print() { System.out.println("父类的print方法"); } } // 子类 class Child extends Parent { @Override public void print() { System.out.println("子类的print方法"); } } public class Main { public static void main(String[] args) { Parent parent = new Parent(); Child child = new Child(); parent.print(); // 输出:父类的print方法 child.print(); // 输出:子类的print方法 } }
在上面的示例中,Parent
类有一个print
方法,在Child
类中使用@Override
注解覆盖了父类的print
方法,并改变了其实现。在main
方法中,创建了一个Parent
对象和一个Child
对象,并分别调用了它们的print
方法。由于Child
类覆盖了print
方法,所以调用child.print()
时将调用子类中的方法,输出为"子类的print方法"。而调用parent.print()
时将调用父类中的方法,输出为"父类的print方法"。