有什么方法可以操作Java中的构造函数吗?
我目前正在做我的作业,但我陷入了困境。任务是根据此图表创建一个程序。在该图中,正如您所看到的,没有创建构造函数的行为,但是在给定的 Main Class< /a> 有。有没有一种方法可以创建程序而不更改给定的主类,并且除了给定的图表之外不创建新方法。该程序用于计算密度。帮助:)
这是我的 Box 类代码:
class Box {
private double width;
private double height;
private double depth;
private double mass;
private double density;
public void setWidth(double width){
this.width = width;
}
public void setHeight(double height){
this.height = height;
}
public void setDepth(double depth){
this.depth = depth;
}
public void setMass(double mass){
this.mass = mass;
}
public double getDensity(){
density = mass / (width * height * depth);
return density;
}
}
I'm currently working on my assignment and I'm stuck rn. The task is to create a program based on this diagram. In that diagram, as you can see, there is no behavior for creating constructors, but in the given Main Class there is. Is there a way to create a program without changing the given Main Class and not creating new methods in addition to the given diagram. The program is to calculate density. Help : )
This is my Box class code:
class Box {
private double width;
private double height;
private double depth;
private double mass;
private double density;
public void setWidth(double width){
this.width = width;
}
public void setHeight(double height){
this.height = height;
}
public void setDepth(double depth){
this.depth = depth;
}
public void setMass(double mass){
this.mass = mass;
}
public double getDensity(){
density = mass / (width * height * depth);
return density;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
仅当
Box
方法具有Box(double, double, double)
构造函数时,您所获得的Main
类才会起作用。因此您必须添加一个。
与 UML 片段的明显矛盾很容易解释。 UML 类图通常不显示构造函数。我的猜测是,无论创建该图的人都不想用多余的细节来混乱它。
但事情是这样的。无论图表显示什么,您的
Box
类都无法与该Main
类一起使用,除非Box
类提供main
方法将使用的构造函数。回答标题中的问题
不,没有。至少……不是我认为你的意思。
理论上,您可以使用“字节码操作”技巧在编译后注入额外的构造函数,但在这种情况下这将是错误的解决方案。
The
Main
class you have been given will only work if theBox
method has aBox(double, double, double)
constructor.So you MUST add one.
The apparent contradiction with the UML snippet is easy to explain. UML class diagrams frequently don't show constructors. My guess is that whoever created that diagram didn't want to clutter it with superfluous detail.
But here is the thing. Irrespective of what the diagram says, your
Box
class cannot work with thatMain
class unless theBox
class provides the constructors that themain
method is going to use.To answer the question in the title
No there isn't. At least ... not in the sense that I think you mean.
In theory, you could use "byte code manipulation" tricks to inject an extra constructor after compilation, but that would be the wrong solution in this context.