函数可以在类的字段中使用吗(java)
如果我有一个抽象类,将函数放入其中一个字段中是否正确?还是会引起问题?
例子:
public abstract class A{
private double x = z+w/y;
....
If I have an abstract class, is it proper form to put a function in one of the fields? or will it cause problems?
example:
public abstract class A{
private double x = z+w/y;
....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
事实上,您没有放置一个函数,而是放置一个表达式作为初始值设定项。使用它并没有什么不好。
但请注意,如果您的表达式依赖于其他字段,则该值取决于初始化顺序。 (有关高级详细信息,请参阅此答案例子)
Indeed, you put not a function, just an expression as initializer. There is nothing bad in using it.
Beware however that if your expression depends on other fields, the value depends on the initialization order. (See this answer for advanced details and example)
简而言之,这取决于。
是的,您可以从技术角度做到这一点 - 如果在阅读代码时非常清楚发生了什么并且没有发生任何意外情况(即它不会变成下一个 Java 谜题),那么就可以了。但请记住,如果您将这种事情推向极端,它可能会变成一个真正的难题(例如,它可能取决于初始化的顺序字段),而这就是应该避免的时候!
In short, it depends.
You can do it from a technical perspective, yes - and if it's very clear what's going on and nothing unexpected happens when reading through the code (i.e. it doesn't turn into the next Java puzzler) then it's fine. Bear in mind though that if you take this sort of thing to extremes it can turn into a real puzzle (it can be dependant on the order fields are initialised in for instance) and that's when it should be avoided!