Referencing of Instances

Class A { // some code here}
class B { // some code here}

class Ex {

public static void main(string args[]) {

A a=new B();
B b=new A();
a.add();
b.add();
}
Will this program run?
Explain the referencing the object instances.
What is the result;

Questions by akhisharma   answers by akhisharma

Showing Answers 1 - 6 of 6 Answers

foiaz

  • Dec 27th, 2007
 

Yes, this program will execute. Reference variables a and b holds the object instance of Class B and Class A respectively. i.e it points to the memory locations of those objects.

a.add() will call the add() method of Class B. and b.add() will call the add() method of Class A.

  Was this answer useful?  Yes

No it will not compile - as A does not extend B nor vice-versa when you try to assign an object of type B to a reference of type A (and vice-versa) you will get an 'Incompatible type' error message from the compiler! If inheritance were involved that would be a different matter - I do not understand why people put the wrong answers - this is supposed to help people - all you needed to do was write the code and test it before answering.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions