jQuery in Action, 2nd edition*
The moose likes Web Component Certification (SCWCD/OCPJWCD) and the fly likes Hello, design pattern question... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Web Component Certification (SCWCD/OCPJWCD)
Bookmark "Hello, design pattern question..." Watch "Hello, design pattern question..." New topic

Hello, design pattern question...

Carmen Brianick
Ranch Hand

Joined: Feb 23, 2006
Posts: 67
Hi, I have a question about interfaces. I've read in HFSJ Design Patterns chapter that one of the code design goals is to have loosely coupled code, where for example if code A wants to use code B, then there should be an interface between them. Code B would implement this interface so that Code A would use the interface to communicate with code B methods.

I think this is what the statement means:

Interface called TestInterface would contain a sample method like:
public int addNumbers(int a, int b);

Code B would implement TestInterface, so it would have same method:
public int addNumbers(int a, int b){ return a + b; }

*** Please excuse any wrong syntax.

1.) My question is, is the below what is meant by "Code A would use the interface to communicate with code B methods."?
TestInterface inter = new B();

2.) If my interpretation is wrong, can you please provide a simple code example of this?

3.) If my interpretation is true, then why would I need an interface, can't I just do something like:
B bObj = new B();

Thanks so much for your help! I've been hammering this for some time with no luck!

Gab Buda

Joined: Mar 25, 2006
Posts: 24
Hi Carmen,

Since the "code A" uses an interface to access "code B", it will NOT have directly access to code B; it uses only the interface's methods. So, instead of

TestInterface inter = new B();

you'll use:

TestInterface inter = SomeFactoryClass.getInstance();

and in the method getInstance() you will create an object having the type B. When you'll decide to replace "code B" with another implementation ("code C" which also implements TestInterface), all that you'll need to do is to change the factory's method implementation (it will create and return a "code C" instance).

Hope this helps

[ April 02, 2006: Message edited by: gabb buda ]
[ April 02, 2006: Message edited by: gabb buda ]

SCJP 1.4 (85%)<br />SCWCD 1.4 (94%)
Carmen Brianick
Ranch Hand

Joined: Feb 23, 2006
Posts: 67
Hi gabb! Thanks so much for your great explaination. I'll take some time to think through too!

Thanks again,
I agree. Here's the link: http://aspose.com/file-tools
subject: Hello, design pattern question...
Similar Threads
Method-local Inner Class Q
Inner class and misc Q
q on interfaces
Sun Guoqio's Mock 2 (anonymous class)
Checked exception and interface.