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"); } } 
  • four
    Car myBondCar = new Car (); well, so you can create new JamesBondCar () - pavel

1 answer 1

In both cases, you create an object of the parent class Car , therefore the result is appropriate. Just replace

 Car myBondCar = new Car(); 

on

 Car myBondCar = new JamesBondCar (); 
  • A counter question to you, what's the difference in creating an object: JamesBondCar myBondCar = new JamesBondCar (); and your option. I know that Car (in your case) or JamesBondCar at the beginning of the line - play the role of a new type of variable - salt en
  • Here, my friend, the very basics of inheritance must be understood. The teacher from me is so-so, it’s better to see something like this: developer.alexanderklimov.ru/android/java/extends.php . But briefly: the left indicates what can be written into this variable and how it will be perceived; on the right, what is actually written there. - Riĥard Brugekĥaim
  • In other words, specifying Car to the left we can write there an object of this class or any child, but only those methods that were defined in the Car class will be available (if we add another method to the JamesBondCar that is not in the Car class, it will not be it is seen). In turn, when writing to a variable of a Car object, it will produce results as Car, and if you write JamesBondCar, then the result will be appropriate for this class. - Riĥard Brugekĥaim