Creating Methods
We've already talked about methods and how to create them.
Here's a quick example of a method that does some calculation, and prints the result:
public static void doMath(int x) {
x += 17;
x *= 4;
x %= 2;
System.out.println(x);
}
Getter Methods
Getter methods allow us to get the object attributes of each object. These are non-void, as they return a value.
Here's an example of a Getter Method:
public String getColor() {
return color;
}
And in our main method, we can use it like this:
System.out.println(tesla.getColor()); // prints Red
System.out.println(motorcycle.getColor()); // prints Blue
System.out.println(malibu.getColor()); // prints Silver
You will want to create a Getter method for every variable you want to access after creating the object.
Setter Methods
Setter methods allow us to set the object attributes of each object. These are void, as they do not return a value.
Here's an example of a Setter Method:
public String setColor(String color) {
this.color = color;
}
And in our main method, we can use it like this:
tesla.setColor("White");
motorcycle.setColor("Black");
malibu.setColor("Gray");
System.out.println(tesla.getColor()); // prints White
System.out.println(motorcycle.getColor()); // prints Black
System.out.println(malibu.getColor()); // prints Gray
You will want to create a Setter method for every variable you want to change after creating the object.
toString()
And, of course, the toString() method. This is built into every object, just by putting it in a print or println.
We write a toString() like so:
public String toString() {
String message;
if(isElectric) {
message = "is electric";
} else {
message = "is not electric";
}
return "This vehicle is a " + color + " " + model + " " + type + " that " + message + " and costs $"+cost+".";
}
And call it in the main method like this:
System.out.println(tesla);
System.out.println(motorcycle);
System.out.println(malibu);
This prints:
This vehicle is a Red Tesla Model 3 Sedan that is electric and costs $35000.
This vehicle is a Blue Harley-Davidson LiveWire Motorcycle that is electric and costs $30000.
This vehicle is a Silver Chevy Malibu Sedan that is not electric and costs $23000.
Try playing with Getter/Setter and toString() methods, and see what you can do!