117k views
0 votes
Public class Car {

public void m1() {
System.out.println("car 1");
}
â
public void m2() {
System.out.println("car 2");
}
â
public String toString() {
return "vroom";
}
}


public class Truck extends Car {
public void m1() {
System.out.println("truck 1");
}
}

And assuming that the following variables have been declared:

Car mycar = new Car();
Truck mytruck = new Truck();

What is the output from the following statements?

a. Sound F/X System.out.println(mycar);
b. mycar.m1();
c. mycar.m2();
d. System.out.println(mytruck);
e. mytruck.m1();
f. mytruck.m2();

User Norbekoff
by
5.1k points

1 Answer

6 votes

Answer:

The Following are the outputs:

a. vroom

b. car 1

c. car 2

d. vroom

e. truck 1

f. car 2

Step-by-step explanation:

The first statement System.out.println(mycar); prints an instance of the Car object my car which calls the toString() method.

The second statement mycar.m1(); Calls the method m1() which prints car1

The third statement mycar.m2(); calls the method m2() which prints car2

Then another class is created Truck, and Truck inherits all the methods of Car since it extends Car. Truck has a method m1() which will override the inherited method m1() from the Car class.

The fourth statement System.out.println(mytruck); will print print vroom just as the first statement since it inherits that method toString()

The fifth statement calls m1() in the Truck class hence prints Truck 1

Finally the sixth statement will print car 2 because it also inherited that method and didnt overide it.

User Peter Suwara
by
5.4k points