My Object is not been printed

时间:2017-04-09 23:56:38

标签: java object

I'm new to Java and trying to make a simple program which holds track of the fuel usage. I thought this would be a good exercise.

public class MyJavaProgram {

    static Car myCar = new Car("Audi");

    public static void main(String[] args) {

        System.out.println(myCar);

        myCar.refuel(100);
        myCar.drive(50);
        myCar.drive(20);

    }

}

Normally in Java this code would print out something like: "package.Animal@", but here is what I get in my console:

> A new Audi has been created.
> 
> Car refilled with 100 liter fuel. 
> Car drove 50 km. 
> Car drove 20 km.

My Car class:

public class Car {

    String type;
    int fuel = 0;
    int driven;

    public Car(String type) {
        this.type = type;
        System.out.println("A new "+type+" has been created.");
    }

    public void refuel(int amount) {
        fuel += amount;
        System.out.println("Car refilled with "+amount+ " liter fuel.");
    }

    public void drive(int amount) {
        fuel -= amount;
        driven += amount;
        System.out.println("Car drove "+amount+" km.");
    }

    public String toString() {
        return "";
    }

}

I can not see what part of my code causes this bug.

3 个答案:

答案 0 :(得分:3)

I'm not a java wizard myself but i imagine its this little guy right here:

public String toString() {
    return "";
}

The println thingamabob probably calls the objects toString() method which you have made return an empty string rather than the default.

Get rid of that or change it and you should be golden

答案 1 :(得分:1)

Your object is printed. it is only that you have overriden the toString method with returns an empty string.

答案 2 :(得分:0)

If you'd like java to invoke the default toString() method, you shouldn't define your own toString() method. Your toString() method returns an empty string, so an empty string gets printed to the console.