Overloading methods
A central aspect of Polymorphism is overloading, which allows object instances created from your classes to exist in different forms. You will implement a second way to drive to enable the Tesla
to drive backward. This is a case of method overloading, where we want a functionality to possess different forms within the same class.
This exercise is part of the course
Introduction to Object-Oriented Programming in Java
Exercise instructions
- Create a second
public
void
method,drive
that takes aboolean
parameterisDrivingBackward
. - Inside the new
drive
method, print the message"driving backward"
. - Call the second
drive
method using themyTesla
object instance with the parameter valuetrue
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
public class Main {
static class Tesla {
public void drive() {
System.out.println("drive normally");
}
// Create second drive method with parameter isDrivingBackward
____ ____ ____(____ ____){
____.____.____(____);
}
}
public static void main(String[] args) {
Tesla myTesla = new Tesla();
myTesla.drive();
// Call second drive method
____.____(____);
}
}