The question is:
Suppose o
is a reference of type Object
that is pointing to a type A
object that contains a f
method and a toString
method. Both toString
and f
have no parameters. show the statement that calls the toString
method and the statement that calls the f
method.
is the answer:
f();
toString();
No, that's not right. First of all, you're not using the instance o
to invoke the methods. Without specifying an instance the compiler would cause those methods to be implicitly called on this
.
Second, you can't invoke o.f()
since f
is not a method of Object
. An explicit cast is required to tell the compiler that o
is of type A
.
Object o = new A();
String s = o.toString();
((A)o).f();
Depends on the scope in which you are invoking the function. If you are calling f
and toString
in instance methods of the A
class, then you are correct.
If you are calling f
and toString
in static methods of the A
class, or any method of other classes, then you will need to instantiate a new A
object, then call the functions on it, like so:
A myA = new A(); // Assuming the existence of a no-args constructor
myA.f();
myA.toString();
If your reference is strictly of the type Object
, then you cannot invoke f
, unless you first cast it to type A
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With