Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exam sample, curious if i got it right

Tags:

java

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();
like image 201
user1096713 Avatar asked Dec 19 '11 04:12

user1096713


2 Answers

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();

See Also

  • Inheritance (the Java Tutorials)
like image 126
Mark Peters Avatar answered Oct 04 '22 11:10

Mark Peters


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.

like image 36
Jon Newmuis Avatar answered Oct 04 '22 09:10

Jon Newmuis