137k views
5 votes
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

User Caxix
by
6.0k points

1 Answer

1 vote

Answer:

Hi there KatiesTomato! The answer is: b. II

Step-by-step explanation:

Java allows us to override a method defined in the main or Parent class by re-defining it in the child class. In the question, the first option gives us code that will throw an error because the String method getValue() in class B is being overridden by a method in class A which returns an Object which is also a String. So the compiler will throw an error that type Object is not compatible with String. Option 2 will compile successfully and return a String because the Object is allowed to be converted to a String.