Code Editor
Object-Oriented Java

Methods: II

Fantastic! Similar to constructors, you can customize methods to accept parameters.

class Car { int modelYear; public Car(int year) { modelYear = year; } public void startEngine() { System.out.println("Vroom!"); } public void drive(int distanceInMiles) { System.out.println("Miles driven: " + distanceInMiles); } public static void main(String[] args){ Car myFastCar = new Car(2007); myFastCar.startEngine();; }

In the example above, we create a drive method that accepts an int parameter called distanceInMiles. In the main method, we call the drive method on the myFastCar object and provide an int parameter of 1628.

Calling the drive method on myFastCar will result in printing Miles driven: 1628 to the console.

Report a Bug
If you see a bug or any other issue with this page, please report it here.