Recall inheritance syntax: public class class-name extends super-class { ... } A
ID: 3637725 • Letter: R
Question
Recall inheritance syntax:public class class-name extends super-class {
...
}
A subclass inherits all the superclass's behaviors, but can override these behaviors. To call an overriden method, use the keyword super: super.method-name(...)
Consider the following class definitions:
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");
}
}
What is the output from the following code segment?
Truck mycar = new Truck();
System.out.println(mycar);
mycar.m1();
mycar.m2();
Explanation / Answer
What is the output from the following code segment? Truck mycar = new Truck();----------------------create the object of Truck class System.out.println(mycar);-----------------------This will call toString() and it will print"vroom" mycar.m1();----------------------------------------- Here the m1() of derived class wil be called, so print " truch 1" mycar.m2();------------------------------------------ Here it will search for m2() in the derived class and as it doesn't find the function then it will search for base class . So it will print "car 2" So as a result of the program is: vroom truck1 car2
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.