143k views
5 votes
Suppose a class Car and its subclass Honda both have a method called speed as part of the class definition. rentalH refers to an object of the type Honda and the following statements are found in the code: rentalh.cost(); super.speed(); what will the first statement do?

A. Nothing will be called since the code will not compile as a result of multiple definitions of speed.
B. The cost method in Car will be called.
C. The cost method in Honda will be called.
D. Overloading will be used to determine which cost method to use.

2 Answers

6 votes

Final answer:

The statement rentalh.cost(); will call the cost method in Honda if it is defined there; otherwise, it will call the cost method from the Car class due to inheritance. The separate mention of super.speed(); is unrelated to the execution of the cost method.

Step-by-step explanation:

When the statement rentalh.cost(); is found in the code, it will attempt to call the cost method on the object referred to by rentalh. Assuming rentalh is an object of the subclass Honda, which is a subclass of Car, the behavior of the code depends on whether the method cost is defined in Honda, the subclass, or not.

If the cost method is defined within the subclass Honda, then this method will be executed. If it is not defined within Honda, but is defined in the parent class Car, then the superclass version of the method will be called instead. Thus, the correct answer to what the first statement will do is:

  • C. The cost method in Honda will be called. If Honda does not define a cost method, then the cost method in Car will be called due to inheritance.

The mention of super.speed(); is irrelevant to what the first statement does and appears to be a separate line of code that would call the overridden speed method from the superclass of the context in which it is executed, which is not necessarily related to the cost method or the instance rentalh.

User Mansuro
by
3.7k points
5 votes

Answer:

C. The cost method in Honda will be called.

Step-by-step explanation:

The first statement will cause the cost method in Honda to be called. This is because rentalh is a object of the subclass Honda. Therefore, any method that is called using this object variable will target the elements within the Honda subclass. In this case, the cost() method is being called using the rentalh variable which will look for the cost() method within the scope of the Honda subclass. In order to target the parent class Car it would need to be called using the super variable as in statement 2.

User Forhad
by
3.1k points