aspose file tools
The moose likes Java in General and the fly likes using interfaces as reference variable Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "using interfaces as reference variable" Watch "using interfaces as reference variable" New topic
Author

using interfaces as reference variable

Shay Levy
Greenhorn

Joined: Oct 01, 2009
Posts: 7
Hi,


(1) interface A {}
(2) class B implements A{}

(3) A a = new B();
(4) B b = new B();

is there any diffrence between statement (3) and (4)? Is the declaration of (3) better (due to polomorphism) ? do I gain anything by using (3) instead of (4)? or did I just miss something really basic?

Thanks
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32712
    
    4
Welcome to JavaRanch

You find (3) has an advantage when you haveandThen you can easily change "new B()" to "new C()" or "new D()" and retain all your functionality.
Shay Levy
Greenhorn

Joined: Oct 01, 2009
Posts: 7

Thanks for the reply.

Embla Tingeling
Ranch Hand

Joined: Oct 22, 2009
Posts: 237
Shay Levy wrote:Is the declaration of (3) better (due to polomorphism) ?


There's a design criterion saying: Use the highest abstraction level (upwards in the inheritance tree) that meets your needs.

Writing code using A variables will definately make your code more flexible and general because it will work with any subtype of A like B (and C and D and ....).

On the other hand the subtypes B and C and D may not be equally efficient when objects of these types are plugged into an algorithm written using A variables. Say B is excellent but C and D are disasters. In that case the A abstraction is too high and you should write your code using B variables instead.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: using interfaces as reference variable
 
Similar Threads
configuring J2EE environment variables
Head First Java exercise problem
Question on Array
Explanation Required
how to create a boolean truth table