[英]when calling method from another class - retuns an incomprehensible value JAVA
When i run 2nd class i see " Car@15ab7626 " why ? 当我上二等班时,为什么会看到“ Car @ 15ab7626”? in teory i must see 20, yes? 在课程中,我必须看到20,是吗? I have alredy used differnet combinatoin & ask google but dont understent why. 我已经使用了differnetnet combinatoin和询问谷歌,但不要理解为什么。
i have 1 class 我有1节课
public class Car {
public int drive(int a) {
int distance = 2*a;
return distance;
}
}
and 2nd class 和二等
public class CarOwner {
public static void main(String[] args) {
Car a = new Car();
a.drive(10);
System.out.println(a);
}
}
You are printing the car object, not the result printed by drive 您正在打印汽车对象,而不是驱动器打印的结果
That incomprehensible value JAVA is textual representation of Object. 不可理解的值JAVA是Object的文本表示形式。
When you do System.out.println(a);
当您执行System.out.println(a);
then by default toString()
method calls on passed object.
然后默认情况下, toString()
方法对传递的object.
调用object.
As per docs of toString () 根据toString ()的文档
Returns a string representation of the object. 返回对象的字符串表示形式。 In general, the toString method returns a string that "textually represents" this object. 通常,toString方法返回一个“以文本形式表示”此对象的字符串。
So 所以
Car@15ab7626
is the textual representation of Values class. Car@15ab7626
是Values类的文本表示形式。
To print result which is returned by your drive()
method, print, 要打印由drive()
方法返回的结果,请打印,
System.out.println(a.drive(10));
If you want to print the result from the drive()
method, assign the result to a variable and then print it. 如果要打印来自drive()
方法的结果,请将结果分配给变量,然后打印。
int result = a.drive(10);
System.out.println("Result = " + result);
or directly pass the result to the System.out.println()
method; 或直接将结果传递给System.out.println()
方法;
System.out.println("Result = " + a.drive(10));
If you want to print the a
object in a readable way, override the toString()
method in the Car
class definition. 如果您想打印a
对象以可读的方式,覆盖toString()
的方法, Car
类定义。
@Override
public String toString() {
return "This is a car"; //for example
}
You are returning the value you have from a drive method, but you're not printing it. 您正在从驱动器方法返回值,但没有在打印它。
To print out the value of the drive method, use 要打印驱动方法的值,请使用
public class CarOwner {
public static void main(String[] args) {
Car a = new Car();
System.out.println(a.drive(10));
}
}
That's not the way method return values work. 这不是方法返回值的工作方式。 If you want to see the result as 20, replace your SOP with the following 如果您想将结果显示为20,请使用以下代码替换SOP
System.out.println(a.drive(10));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.