在构造器里调用可重写的方法有什么问题?

问题:在构造器里调用可重写的方法有什么问题?

我有一个检票页面的类通过抽象方法的结果去去设置页的标题

public abstract class BasicPage extends WebPage {public BasicPage() {add(new Label("title", getTitle()));}protected abstract String getTitle();}

NetBeans就警告我"Overridable method call in constructor"这个信息,但是这是什么错误鸭?
我能想到的唯一替代方案就将抽象方法的结果传递给子类的父类构造器,但是很多参数就无法读取了

回答一

下面有一个帮助你理解的例子

public class Main {static abstract class A {abstract void foo();A() {System.out.println("Constructing A");foo();}}static class C extends A {C() { System.out.println("Constructing C");}void foo() { System.out.println("Using C"); }}public static void main(String[] args) {C c = new C(); }
}

如果你跑一下上面的代码,就会得到下面的结果

Constructing A
Using C
Constructing C

看到了吗?foo()使用到了C,在C的构造函数开始跑之前。如果foo()要求c有一个确定的状态(构造函数已经完成了),那么就会遇到一个C未被定义的状态,就会直接失败了。因此你不能确定A里面可重写的foo()需要什么,你就会碰到一个警告了。

回答二

下面这个例子揭露了当在父类构造器中调用一个可重写的方法可能出现的逻辑问题

class A {protected int minWeeklySalary;protected int maxWeeklySalary;protected static final int MIN = 1000;protected static final int MAX = 2000;public A() {setSalaryRange();}protected void setSalaryRange() {throw new RuntimeException("not implemented");}public void pr() {System.out.println("minWeeklySalary: " + minWeeklySalary);System.out.println("maxWeeklySalary: " + maxWeeklySalary);}
}class B extends A {private int factor = 1;public B(int _factor) {this.factor = _factor;}@Overrideprotected void setSalaryRange() {this.minWeeklySalary = MIN * this.factor;this.maxWeeklySalary = MAX * this.factor;}
}public static void main(String[] args) {B b = new B(2);b.pr();
}

结果可能是:

minWeeklySalary: 0maxWeeklySalary: 0

这是因为B的构造器第一次调用A的构造器,B里面可重写的方法就会被执行。但是里面执行的方法需要使用到我们实例的变量,但是我们实例的变量还未被初始化(因为A的构造器还没完成执行),因为这个变量的值0,而不是1也没有被定义为2(程序员可能认为是这样的)。如果这种逻辑推导要干十多次的话,那就很难去追踪一个错误了

我希望这对你是有帮助的

文章翻译自Stack Overflow:https://stackoverflow.com/questions/3404301/whats-wrong-with-overridable-method-calls-in-constructors

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/390955.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

创建hugo博客_如何创建您的第一个Hugo博客:实用指南

创建hugo博客Hugo is a great tool to use if you want to start a blog.如果您想创建博客,Hugo是一个很好的工具。 I use Hugo myself for my blog, flaviocopes.com, and Ive been using it for more than two years. I have a few reasons for loving Hugo.我本…

Python自动化开发01

一、 变量变量命名规则变量名只能是字母、数字或下划线的任意组合变量名的第一个字符不能是数字以下关键字不能声明为变量名 [and, as, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not,…

记录关于vs2008 和vs2015 的报错问题

出现了 VS2008无法创建项目,无法打开项目的情况,提示这个注册表键值有问题 HKEY_LOCAL_MACHINE \ SOFTWARE \ Microsoft \ MSBuild \ ToolsVersions \ 14.0, 但是查看了注册表没有这个键。费尽辛万苦,中午在思密达的一个网站上看到…

未越狱设备提取数据_从三星设备中提取健康数据

未越狱设备提取数据Health data is collected every time you have your phone in your pocket. Apple or Android, the phones are equipped with a pedometer that counts your steps. Hence, health data is recorded. This data could be your one free data mart for a si…

怎么样用System.out.println在控制台打印出颜色

问题:怎么样用System.out.println在控制台打印出颜色 怎么样才能在控制台里打印颜色啊?我想要展示一些有颜色的字体,当处理器发送数据和接收数据的时候,也使用不同颜色的字体。 回答一 在这个Java类里面带有public static 的数…

sql注入语句示例大全_SQL Order By语句:示例语法

sql注入语句示例大全Order By is a SQL command that lets you sort the resulting output from a SQL query.Order By是一个SQL命令,可让您对SQL查询的结果输出进行排序。 订购依据(ASC,DESC) (Order By (ASC, DESC)) ORDER BY gives us a way to SORT…

[BZOJ2599][IOI2011]Race 点分治

2599: [IOI2011]Race Time Limit: 70 Sec Memory Limit: 128 MBSubmit: 3934 Solved: 1163[Submit][Status][Discuss]Description 给一棵树,每条边有权.求一条简单路径,权值和等于K,且边的数量最小.N < 200000, K < 1000000 Input 第一行 两个整数 n, k第二..n行 每行三…

分词消除歧义_角色标题消除歧义

分词消除歧义折磨数据&#xff0c;它将承认任何事情 (Torture the data, and it will confess to anything) Disambiguation as defined in the vocabulary.com dictionary refers to the removal of ambiguity by making something clear and narrowing down its meaning. Whi…

北航教授李波:说AI会有低潮就是胡扯,这是人类长期的追求

这一轮所谓人工智能的高潮&#xff0c;和以往的几次都有所不同&#xff0c;那是因为其受到了产业界的极大关注和参与。而以前并不是这样。 当今世界是一个高度信息化的世界&#xff0c;甚至我们有一只脚已经踏入了智能化时代。而在我们日常交流和信息互动中&#xff0c;迅速发…

创建字符串枚举的最好方法

问题&#xff1a;创建字符串枚举的最好方法 用一个枚举类型去表示一组字符串的最好方法是什么 我尝试这样&#xff1a; enum Strings{STRING_ONE("ONE"), STRING_TWO("TWO") }我怎么样才可以像使用字符串那样使用它们&#xff1f; 回答一 我不知道你想…

网络安全习惯_健康习惯,确保良好的网络安全

网络安全习惯In a similar fashion to everyone getting the flu now and again, the risk of catching a cyberattack is a common one. Both a sophisticated social engineering attack or grammatically-lacking email phishing scam can cause real damage. No one who c…

attr和prop的区别

由于prop(property的缩写)和attr(attribute的缩写)翻译成汉语&#xff0c;均有“特性、属性”等意思的原因&#xff0c;导致大家容易混淆分不清。 (1)在处理自定义时属性时&#xff0c;用attr()&#xff0c;若用prop(),则结果为undefined&#xff1b; (2)DOM固有属性&#xff0…

15行Python代码,帮你理解令牌桶算法

在网络中传输数据时&#xff0c;为了防止网络拥塞&#xff0c;需限制流出网络的流量&#xff0c;使流量以比较均匀的速度向外发送&#xff0c;令牌桶算法就实现了这个功能&#xff0c;可控制发送到网络上数据的数目&#xff0c;并允许突发数据的发送。 什么是令牌 从名字上看令…

在Java中,如何使一个字符串的首字母变为大写

问题&#xff1a;在Java中&#xff0c;如何使一个字符串的首字母变为大写 我使用Java去获取用户的字符串输入。我尝试使他们输入的第一个字符大写 我尝试这样: String name;BufferedReader br new InputStreamReader(System.in);String s1 name.charAt(0).toUppercase());…

在加利福尼亚州投资于新餐馆:一种数据驱动的方法

“It is difficult to make predictions, especially about the future.”“很难做出预测&#xff0c;尤其是对未来的预测。” ~Niels Bohr〜尼尔斯波尔 Everything is better interpreted through data. And data-driven decision making is crucial for success in any ind…

javascript脚本_使用脚本src属性将JavaScript链接到HTML

javascript脚本The ‘src’ attribute in a tag is the path to an external file or resource that you want to link to your HTML document.标记中的src属性是您要链接到HTML文档的外部文件或资源的路径。 For example, if you had your own custom JavaScript file named …

阿里云ESC上的Ubuntu图形界面的安装

系统装的是Ubuntu Server 16.04 64位版的图形界面&#xff0c;这里是转载的一个大神的帖子 http://blog.csdn.net/dk_0228/article/details/54571867&#xff0c; 当然自己也再记录一下&#xff0c;加深点印象 1.更新apt-get 保证最新 apt-get update 2.用putty或者Xshell连接远…

leetcode 1269. 停在原地的方案数(dp)

示例 1&#xff1a; 输入&#xff1a;steps 3, arrLen 2 输出&#xff1a;4 解释&#xff1a;3 步后&#xff0c;总共有 4 种不同的方法可以停在索引 0 处。 向右&#xff0c;向左&#xff0c;不动 不动&#xff0c;向右&#xff0c;向左 向右&#xff0c;不动&#xff0c;向…

JavaScript Onclick事件解释

The onclick event in JavaScript lets you as a programmer execute a function when an element is clicked.JavaScript中的onclick事件可让您作为程序员在单击元素时执行功能。 按钮Onclick示例 (Button Onclick Example) <button onclick"myFunction()">C…

近似算法的近似率_选择最佳近似最近算法的数据科学家指南

近似算法的近似率by Braden Riggs and George Williams (gwilliamsgsitechnology.com)Braden Riggs和George Williams(gwilliamsgsitechnology.com) Whether you are new to the field of data science or a seasoned veteran, you have likely come into contact with the te…