Using of object in the interface reference...

Hi friends,I need to know wat is the usage of storing the object in the interface reference....For eg...Interface x which is implemented by class B.Is there any advantage by using the Class B object stored in the interface reference...
[242 byte] By [83Krisha] at [2007-11-27 9:23:39]
# 1

It is not quite clear what you mean.

Generally it is better to program against an interface rather than against the implementation.

List l = new ArrayList(); // so it is better, you can change the implementation

ArrayList l = new ArrayList(); // worse

However sometimes we retain the whole type information:

MyType m = new MyType (); // this could be better than

Cloneable m = new MyType (); // worse

BIJ001a at 2007-7-12 22:18:58 > top of Java-index,Java Essentials,Java Programming...
# 2

I assume you're asking why if:

interface X {}

class B implements X {}

then it's good to do this:

X aVar = new B();

as opposed to:

B aVar = new B();

It's good because it encourages code that defines what a code does as opposed to how it does it. Or to put it another way, it results in designs that are about abstract types and not specific implementations. This generally results in more flexible code.

But note:

1) you're not really "storing" the B object in aVar; aVar is just a reference to an object of B.

2) the above example isn't the best example of coding to an interface. A better example is something like return values or parameters. That is to say, given the above example:

X aMethod() {}

is better than

B aMethod() {}

and

void anotherMethod(X param);

is better than

void anotherMethod(B param);

The difference is more significant here, because the flexibly is reflected in the API and thus the larger design. Whereas, the type of a local variable or a (hopefully private) field is basically an implementation detail.

paulcwa at 2007-7-12 22:18:58 > top of Java-index,Java Essentials,Java Programming...