Lesson Weekend

We've learned how objects can help us store and organize related information by storing it in properties. But the real power of objects is that in addition to holding information, they can also do things with that information. A method is essentially a function that is part of an object's blueprint.

In Intro to Programming, you learned about Prototypes for JavaScript objects, and there is similar functionality in Java, although we do not use the term Prototype to describe it; that's a JS specific term. In Java, we just speak of Methods or Object Methods.

Writing Custom Methods for Objects

Generally speaking, when people are looking to buy a car, they set out with a budget. They have a general idea of how much they'd like to spend.

Let's create a method we can call upon a Vehicle that will return whether the vehicle fits within the user's provided budget. It will take the maximum amount a customer is willing to spend, and compare this amount to the price property of a Vehicle. If the vehicle costs less than the customer's budget, the method will return true. If not, it will return false.

car-dealership/Vehicle.java
class Vehicle {
  public int year;
  public String brand;
  public String model;
  public int miles;
  public int price;

    public boolean worthBuying(int maxPrice){
       return (price < maxPrice);
    }

}
  • Here, we define a method called worthBuying() within our Vehicle class. We know this method can only be called on Vehicle objects, because it has been defined specifically in this class.

  • The access modifier public means this method is available to anyone (again, we'll explore access modifiers in depth later on).

  • We also declare that this method will return a boolean type. We use the primitive boolean instead of its corresponding wrapper class Boolean, because we simply do not yet need to call any methods on this return value.

  • We state that our worthBuying() method takes one single argument: maxPrice. We declare this argument to be the int primitive type. maxPrice will represent the most money a customer at our car dealership is willing to spend.

  • Within our method, we simply return the result of (price < maxPrice). price refers to the price attribute of any Vehicle we call this method on. This price is compared to the user-provided maxPrice. Our method will then return true or false depending on whether the user's maxPrice is greater or less than the cost of the vehicle.

Custom Methods in Java Applications

Now, let's add this method to our existing application. Since we'll need to gather information from the user (the maximum price a customer is willing to spend on a car), we'll need to work with our BufferedReader class java.io package.

car-dealership/App.java
import models.Vehicle;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class App {
  public static void main(String[] args) {
  ...
...

Next, we need to ask the user what their budget for a new vehicle is. We'll be using the BufferedReader again to accomplish this.

car-dealership/App.java
public static void main(String[] args) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
   System.out.println("What is your maximum budget for a vehicle?");

   try {

       String stringUserMaxBudget = bufferedReader.readLine();

       Vehicle hatchback = new Vehicle();
       hatchback.year = 1994;
       hatchback.brand = "Subaru";
       hatchback.model = "Legacy";
       hatchback.miles = 170000;
       hatchback.price = 4000;

       Vehicle suv = new Vehicle();
       suv.year = 2002;
       suv.brand = "Ford";
       suv.model = "Explorer";
       suv.miles = 100000;
       suv.price = 7000;

       Vehicle sedan = new Vehicle();
       sedan.year = 2015;
       sedan.brand = "Toyota";
       sedan.model = "Camry";
       sedan.miles = 50000;
       sedan.price = 30000;

       Vehicle truck = new Vehicle();
       truck.year = 1999;
       truck.brand = "Ford";
       truck.model = "Ranger";
       truck.miles = 100000;
       truck.price = 4000;

       Vehicle crossover = new Vehicle();
       crossover.year = 1998;
       crossover.brand = "Toyota";
       crossover.model = "Rav-4";
       crossover.miles = 200000;
       crossover.price = 3500;

       Vehicle[] allVehicles = {hatchback, suv, sedan, truck, crossover};

       int userMaxBudget = Integer.parseInt(stringUserMaxBudget);

       System.out.println("Alright, here's what we have in your price range:");

   ...

   }
   catch(IOException e)
   {
       e.printStackTrace();
   }
}

Remember, all user-provided input comes into our application as String type. That's why stringUserMaxBudget has been declared as String. We then use the Integer.parseInt() method to transform this string back into the int type, since that's what our method is expecting as an argument.

Now, let's call our worthBuying() method. We'll add an if conditional statement in our existing for loop to make sure we only print a vehicle's details if the vehicle is within the customer's budget:

car-dealership/App.java
import models.Vehicle;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class App {
   public static void main(String[] args) {

       BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
       System.out.println("What is your maximum budget for a vehicle?");

       try {
           String stringUserMaxBudget = bufferedReader.readLine();

           Vehicle hatchback = new Vehicle();
           hatchback.year = 1994;
           hatchback.brand = "Subaru";
           hatchback.model = "Legacy";
           hatchback.miles = 170000;
           hatchback.price = 4000;

           Vehicle suv = new Vehicle();
           suv.year = 2002;
           suv.brand = "Ford";
           suv.model = "Explorer";
           suv.miles = 100000;
           suv.price = 7000;

           Vehicle sedan = new Vehicle();
           sedan.year = 2015;
           sedan.brand = "Toyota";
           sedan.model = "Camry";
           sedan.miles = 50000;
           sedan.price = 30000;

           Vehicle truck = new Vehicle();
           truck.year = 1999;
           truck.brand = "Ford";
           truck.model = "Ranger";
           truck.miles = 100000;
           truck.price = 4000;

           Vehicle crossover = new Vehicle();
           crossover.year = 1998;
           crossover.brand = "Toyota";
           crossover.model = "Rav-4";
           crossover.miles = 200000;
           crossover.price = 3500;

           Vehicle[] allVehicles = {hatchback, suv, sedan, truck, crossover};

           int userMaxBudget = Integer.parseInt(stringUserMaxBudget);

           System.out.println("Alright, here's what we have in your price range:");

           for (Vehicle individualVehicle : allVehicles) {
               if (individualVehicle.worthBuying(userMaxBudget)) {
                   System.out.println("----------------------");
                   System.out.println(individualVehicle.year);
                   System.out.println(individualVehicle.brand);
                   System.out.println(individualVehicle.model);
                   System.out.println(individualVehicle.miles);
                   System.out.println(individualVehicle.price);
               }
           }
       }
       catch(IOException e)
       {
           e.printStackTrace();
       }
   }

}



Perfect! Now let's compile and run our program.

Now, if we enter a price like 5000, we should see that our application only prints the details of Vehicle objects if their price attribute is below 5000:

What is your maximum budget for a vehicle?
5000
Alright, here's what we have in your price range:
----------------------
1994
Subaru
Legacy
170000
4000
----------------------
1999
Ford
Ranger
100000
4000
----------------------
1998
Toyota
Rav-4
200000
3500

Process finished with exit code 0


Example GitHub Repo for Car Dealership

Example


car-dealership/Vehicle.java
class Vehicle {
  public int year;
  public String brand;
  public String model;
  public int miles;
  public int price;

  public boolean worthBuying(int maxPrice){
    return (price < maxPrice);
  }
}
  • Here, we define a method called worthBuying() within a Vehicle class. This method can only be called on Vehicle objects.

  • The access modifier public means this method is available to anyone.

  • We declare this method will return a boolean type. We use the primitive boolean instead of its wrapper class Boolean, because we do not need to call any methods on this return value.

  • We state that our method takes a single argument named maxPrice. We declare this argument to be the int primitive type.

  • Within our method, we simply return the result of (price < maxPrice). Which will be a boolean type.