java The getValue() method is overridden in two ways. Which one is correct? 1. p
ID: 3715022 • Letter: J
Question
java
The getValue() method is overridden in two ways. Which one is correct?
1.
public class Test {
public static void main(String[] args) {
A a = new A();
System.out.println(a.getValue());
}
class B {
public String getValue() {
return "Any object";
}
class A extends B {
public Object getValue() {
return "A string";
}
2.
public class Test {
public static void main(String[] args) {
A a = new A();
System.out.println(a.getValue());
}
class B {
public Object getValue() {
return "Any object";
}
class A extends B {
public String getValue() {
return "A string";
}
a.I
b.II
c.Both I and II
d.Neither
I know the answer is B but can you explain why?
Explanation / Answer
ANSWER : Here Option(II) is correct because we should override parent class method not child class as in the second example the retrun type of the get Value () method is string but in the first it is Object.
Object is the superclass of String, so it's fine for a method previously declared to return Objectis refined in a subclass override to return String.
It's fine because any code which only knows about the superclass method is going to use the return value as Object, and it's fine to use any String reference as an Object
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.