Java构造函数使用多种方法重载
发布时间:2020-12-15 01:59:55 所属栏目:Java 来源:网络整理
导读:我在课堂上有一个程序任务.我已经理解了重载的基础知识,但我对一点非常困惑.如何仅从我尝试使用的方法输出?那么让我告诉你代码而不是解释. public class Box { private int length,width,height; public Box(int length){ this.length=length; System.out.p
我在课堂上有一个程序任务.我已经理解了重载的基础知识,但我对一点非常困惑.如何仅从我尝试使用的方法输出?那么让我告诉你代码而不是解释.
public class Box { private int length,width,height; public Box(int length){ this.length=length; System.out.println("Line created with length of" + length + "."); } public Box(int length,int width){ this.length = length; this.width = width; System.out.println("Rectangle created with the length of " + length + " "); System.out.println("and the width of " + width + "."); } public Box(int length,int width,int height){ this.length=length; this.width=width; this.height=height; System.out.println("Box created with the length of " + length + ","); System.out.println("the width of " + width + ","); System.out.println("and the height of " + height +"."); } } class BoxTest { public static void main(String[] args) { Box BoxObject1 = new Box(1,0); Box BoxObject2 = new Box(1,2,0); Box BoxObject3 = new Box(1,3); } } 好的,那么!如何在BoxTest类中调用仅输出给定的内容.例如,使用Box BoxObject1我想输出“用XX长度创建的线”而不是其余的.对于Box Box Object2,我想输出“长度为XX,宽度为XX的矩形”.我不确定接下来要添加什么才能实现.任何帮助将不胜感激. 解决方法
我猜
Box BoxObject1 = new Box(1,3); 本来应该是 Box BoxObject1 = new Box(1); Box BoxObject2 = new Box(1,2); Box BoxObject3 = new Box(1,3); 此时,所有三个调用都调用第三个构造函数(对于某些参数传递0). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |