Task:
Calculate the distance for the Car
class, and the distance for the JamesBondCar
class.
Expected values: for class Car
- 120, for class JamesBondCar
- 360.
The real result in both cases displays 120, that is, it ignores the arithmetic action in the method of drive - distance = howlong * 180;
And it seems to ignore the entire method in the JamesBondCar
class, but it only executes the method from the parent class. And, also, the body of the start method in the class JamesBondCar
is not JamesBondCar
.
Search solutions - Tried to use override and super.method. Assigned a different kind of variable.
Waiting for any information - a direct answer, links, books.
PS Just started learning the language. Thank you for your help.
public class Car{ int distance; public void start(){ System.out.println("Car is starting now"); } public void stop(){ System.out.println("Car is stopped now"); } public int drive(int howlong){ distance = howlong*60; //time * speed return distance; } } public class JamesBondCar extends Car{ public void start(){ System.out.println("I'm James Bond!"); } public int drive(int howlong){ distance = howlong * 180; return distance; } }
I call the class:
public class CarOwner{ public static void main(String[] args){ int distance; Car myCar = new Car(); myCar.start(); myCar.stop(); distance = myCar.drive(2); System.out.println("My distance is " + distance + " now."); Car myBondCar = new Car(); myBondCar.start(); myBondCar.stop(); distance = myBondCar.drive(2); System.out.println("I'm Bond, James Bond." + " And "+ "I have " + distance + " distance"); } }