在Java中,当子类继承父类时,子类可以重写(Override)父类中的方法。重写允许子类提供一个特定的实现,以便在调用该方法时使用子类的版本,而不是父类的版本。这在面向对象编程中是一种常见的做法,因为它允许子类根据需要定制或扩展父类的行为。
要在子类中重写父类的方法,需要遵循以下规则:
protected,那么子类方法可以是protected或public,但不能是private。下面是一个简单的例子,演示了如何在Java中使用protected方法重写:
// 父类
class Parent {
protected void printMessage() {
System.out.println("This is the Parent class message.");
}
}
// 子类
class Child extends Parent {
// 重写父类的printMessage方法
@Override
protected void printMessage() {
System.out.println("This is the Child class message.");
}
}
public class Main {
public static void main(String[] args) {
Parent parent = new Parent();
parent.printMessage(); // 输出:This is the Parent class message.
Child child = new Child();
child.printMessage(); // 输出:This is the Child class message.
// 使用父类引用指向子类对象
Parent parentWithChild = new Child();
parentWithChild.printMessage(); // 输出:This is the Child class message.
}
}
在这个例子中,Child类继承了Parent类,并重写了printMessage方法。当我们使用Child类的对象调用printMessage方法时,将使用子类中定义的实现。当我们使用Parent类的引用指向Child类的对象时,仍然会调用子类中重写的方法。这是因为Java使用动态分派来确定在运行时调用哪个方法实现。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。