0

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);  
    }
}
Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55
  • Look at [this stackoverflow topic](http://stackoverflow.com/questions/11659515/overriding-tostring-method) – Paolo Oct 14 '13 at 08:34

4 Answers4

5

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));
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
3

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
}
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
1

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));
  }
}
eis
  • 51,991
  • 13
  • 150
  • 199
1

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));