?

Algorithms & Data Structures

Free Version

Upgrade subject to access all content

Moderate

When to Use Static Methods

ALGOR-HELVHV

Consider the following Java class.

Which of the methods of this class could be made static? Select ALL that apply.

A static method is a method which can be called without first instantiating an object. For example, Math.random() is a static method of the Math class because it can be called without creating a Math object. Typically, a method should be static when its use is independent of a particular object.

public class Car {

   String make;
   String model;
   String color;
   int mpg;
   int year;

   public Car(String make, String model, String color, int mpg, int year) {
      this.make = make;
      this.model = model;
      this.color = color;
      this.mpg = mpg;
      this.year = year;
   }

   public String  getColor() {
      return color;
   }

   public void setColor(String color) {
      this.color = color;
   }

   public int getMPG() {
      return mpg;
   }

   public Car moreEfficient(Car carA, Car carB) {
      if(carA.getMPG() > carB.getMPG())
         return carA;
      else
         return carB;
   }

   public int getYear() {
      return year;
   }

   public Car oldestCar(Car[] cars) {
      Car oldest = cars[0];
      for(int i = 0; i < cars.length; i++) {
         if(cars[i].getYear() < oldest.getYear())
            oldest = cars[i];
      }
      return oldest;
   }

   public String toString() {
      return year + " " + color + " " + make + " " + model + ", " + mpg + " miles per gallon";
   }
}
A

getColor

B

setColor

C

getMPG

D

moreEfficient

E

getYear

F

oldestCar

G

toString