user1506104
user1506104

Reputation: 7086

Logging / Debugging the state of my objects

Say I have a custom object called Car. All of the fields in it are private.

public class Car {

    private String mName;
    private String mBrand;
    private String mModel;

    public Car(String name, String brand, String model) {
        mName = name;
        mBrand = brand;
        mModel = model;
    }

    // more class methods here
}

When I receive an object of this type, I want to examine the state/value of its fields. The two approaches I do to analyze it are:

  1. create getter methods in my Car class then use it (inside Log.d statement) everytime I want to check
  2. use the debugger in Android Studio or in Eclipse

Is there any other ways to do it with efficiency?

Upvotes: 0

Views: 1313

Answers (1)

user1506104
user1506104

Reputation: 7086

I found this nifty solution in my online class. You can use the toString method of the object. In my case I added

public class Car {
    ...

    @Override
    public String toString() {
        return "Car{" +
                "mName='" + mName + '\'' +
                ", mBrand='" + mBrand + '\'' +
                ", mModel='" + mModel + '\'' +
                '}';
    }
}

Whenever you want to check for your object's state, just do:

Log.d("MainActivity", "Current car: " + carInstance);

Cheers!

Upvotes: 1

Related Questions