使用toString()方法打印

时间:2014-03-23 22:36:55

标签: java string printing tostring

class Box
{
// Instance Variables
double length ,ipsos ;
double width ,mikos ;
double height ,platos;
// Constructors
 public Box ( double side )
{
width = side ;
height = side ;
length = side ;
}
public Box ( double x , double y , double z)
{
    platos = y ;
ipsos = z;
mikos = x ;
}

// Methods
double calculate(double praksi)
{
return 2 * ( width * height +
width * length +
height * length ) ;
}
double volume(double emvadon)
{
return platos*ipsos*mikos ;
}

}

在上面的代码中,我怎样才能创建一个toString()方法,所以我可以返回卷的值并计算??? 我是java的新手,所以请尽可能简单

1 个答案:

答案 0 :(得分:0)

toString()是在Object.class上找到的方法,您编写的所有类都将自动扩展。因此,默认情况下,您的类已经拥有此方法,但它不会返回您期望的内容。您可以覆盖此方法,并使其完全按照您的意愿执行。

如果您尝试使用您的课程,您会发现toString()已经可用:

new Box().toString();

只需为您的班级编写一个具有相同签名的新方法,并添加您自己的代码。

public String toString() {}
相关问题