java-Cannot reduce the visibility of the inherited method from 父类

本文介绍了Java中关于方法可见性的规则,特别是当子类重写父类方法时,子类方法的访问级别不能低于父类的方法。通过示例说明了正确的实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

java-Cannot reduce the visibility of the inherited method from 父类

  1561人阅读  评论(0)  收藏  举报


2014-07-17 10:38 by SchrodingerCat


Java里面,当A类继承B类,在B类里面重写(或叫覆写/override)A类的方法时,有一个规定,那就是:子类的该方法的权限修饰符范围应该是大于等于父类。

  class A{

    protected method() { }

  }

  class B extends A{

    private method(){ }

    //private是错误的,会出现错误提示:Cannot reduce the visibility of the inherited method from B

    //将protected,public或者缺省(不加)都是可以正常编译。

  }


修改后的代码有以下问题 1:mainApp.switchToHomeScene(); // 假设存在返回主页的方法中,mainApp cannot be resolved 2: private void showErrorAlert(String message)中,Cannot reduce the visibility of the inherited method from Controller 3:private void showInfoAlert(String message)中,private void showInfoAlert(String message) Controller类代码为:package opera; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.stage.Stage; import java.io.IOException; import javafx.event.ActionEvent; // 添加必要的导入 public class Controller { protected Stage getCurrentStage(Parent root) { return (Stage) root.getScene().getWindow(); } protected void showErrorAlert(String message) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("错误"); alert.setHeaderText(null); alert.setContentText(message); alert.showAndWait(); } protected void showInfoAlert(String message) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("提示"); alert.setHeaderText(null); alert.setContentText(message); alert.showAndWait(); } protected void switchScene(String fxmlPath) throws IOException { Parent root = FXMLLoader.load(getClass().getResource(fxmlPath)); Stage stage = getCurrentStage(root); stage.setScene(new Scene(root)); stage.show(); } // 添加缺失的事件处理方法 public void handleUserLogin(ActionEvent event) { showInfoAlert("用户登录功能"); // 这里添加实际登录逻辑 } public void handleManagerLogin(ActionEvent event) { showInfoAlert("管理员登录功能"); // 这里添加实际登录逻辑 } public void handleExit(ActionEvent event) { Stage stage = (Stage) ((javafx.scene.control.Button) event.getSource()).getScene().getWindow(); stage.close(); } }
最新发布
06-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值