When i run 2nd class i see " Car@15ab7626 " why ? in teory i must see 20, yes? I have alredy used differnet combinatoin & ask google but dont understent why.
i have 1 class
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.
When you do System.out.println(a);
then by default toString()
method calls on passed object.
As per docs of toString ()
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object.
So
Car@15ab7626
is the textual representation of Values class.
To print result which is returned by your drive()
method, print,
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.
int result = a.drive(10);
System.out.println("Result = " + result);
or directly pass the result to the System.out.println()
method;
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.
@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
System.out.println(a.drive(10));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.