Solved

How to design with Interfaces in Java and use them properly ?

Posted on 2007-12-06
28
268 Views
Last Modified: 2010-03-30
Hi,
I am trying to design with interfaces and use the interfaces properly...
Here is what I am trying to do:
I would like to create an interfaces as:

public interface ErrorHandler {
   
    public void HandleError(Object message); //handle just a message
    public void HandleError(Object message, Throwable throwable); //handle a message alongwith a throwable stackTrace

}

Now, I want to implement the interfaces and use it in my application ?
How can I go about doing that?
Here are the assumption:
I will actually create/send an email message with the message/throwable ....(This is implementation specific... no need to explain this...)

But what I really need is to understand how I really go about implementing and using this interface ?

I found this website to be helpful but can't figure out how I pass the arguments for my interface???????

http://www.artima.com/designtechniques/interfaces3.html


Thanks..
_Esam
0
Comment
Question by:_Esam
  • 9
  • 7
  • 6
  • +3
28 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 20422245
Firstly, your method names should be in camel case. One implementation would be


class X implements ErrorHandler {

    public void handleError(Object message, Throwable t) {

        System.err.println(message);

        t.printStackTrace();

    }

}

Open in new window

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 20422254
(The other message should be there too or it won't compile)
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 20422284
You are working in a good direction, but your purpose is more
important than some design pattern that you want to follow.

An interface FORCES a class to have some methods that supply some service.
That's one side.
At the same time implementing an interface adds a qualification to a class
that makes its objects acceptable to those program pieces that TRUST
that the implementing class does really do something useful when those methods
are called.
So, it's a matter of relying on those services.
To make it easier for the callers, try to offer that, what makes it more useful
to them: throwing an Exception of any kind? Finding a way to publish the message?

Ask yourself this question: what would I demand if somebody else was setting up
this interfacing?

;JOOP!
0
 
LVL 11

Expert Comment

by:spoxox
ID: 20422290
Not hard stuff.

You have your interface in your question. The simplest way to "implement" the interface is

public MyNewClass implements ErrorHandler {
//...here you have a method corresponding to each abstract method from the interface class ErrorHandler
//...ie,
    public void HandleError(Object message) //handle just a message
  {
/...do something
  };
    public void HandleError(Object message, Throwable throwable) //handle a message alongwith a throwable stackTrace
  {
/...do something
  };
}
0
 

Author Comment

by:_Esam
ID: 20422304
Now, I understood this part ..
Now, how do I design a class that uses this interface and uses the interfaces to send the error not the implementation ?
Like: say ... in my application there were some errors and I want to send it using the interface not the implementation...
as in ... Interrogator.makeItTalk(cc);

"src > the url above "

Thanks.
_Esam...

interface Talkative {
 

    void talk();

}
 

abstract class Animal implements Talkative {
 

    abstract public void talk();

}
 

class Dog extends Animal {
 

    public void talk() {

        System.out.println("Woof!");

    }

}
 

class Cat extends Animal {
 

     public void talk() {

        System.out.println("Meow.");

    }

}
 

class Interrogator {
 

    static void makeItTalk(Talkative subject) {

        subject.talk();

    }

}
 

Given this set of classes and interfaces, later you can add a new class to a completely different family of classes and still pass instances of the new class to makeItTalk(). For example, imagine you add a new CuckooClock class to an already existing Clock family: 
 
 

class Clock {

}
 

class CuckooClock implements Talkative {
 

    public void talk() {

        System.out.println("Cuckoo, cuckoo!");

    }

}
 

Because CuckooClock implements the Talkative interface, you can pass a CuckooClock object to the makeItTalk() method: 
 
 

class Example4 {
 

    public static void main(String[] args) {

        CuckooClock cc = new CuckooClock();

        Interrogator.makeItTalk(cc);

    }

}

Open in new window

0
 

Author Comment

by:_Esam
ID: 20422472
Say...
In my application I have an error message:
String errrorStr = "Error occurred while processing X";
Exception ex = new MyException("");

How do I pass these arguments to the interface methods ...thru  a delegate ???

Thanks.
_Esam...
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 20422556
You call the class that implements the interface with them
0
 

Author Comment

by:_Esam
ID: 20422668
Exactly . how so ?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 20422717
errorHandlerImplementer.handleError("This is the error for you!", new RuntimeException());
0
 

Author Comment

by:_Esam
ID: 20422762
I am not convinced somehow ...
This sounds like - implementation specific !!!

What was the purpose of the Interface then ????

I would like it interface specific ...

How I do that ?

Thanks.
_Esam..
0
 

Author Comment

by:_Esam
ID: 20422968
Here is what I have so far:


public interface ErrorHandler {
   
    public void handleError();
   
}


public class ErrorProcessor {
   
    public void processError(ErrorHandler eh){
        eh.handleError();
    }
}


public class FmsErrorHandler implements ErrorHandler{
   

    public void handleError(){
     
        try{
            System.out.println("Sending error message");

        }
        catch(Exception exception){
          exception.printStackTrace();
           
      }
    }
}


public class TestErrorHandler {

    public static void main(String[] args) {
        FmsErrorHandler fmsEH = new FmsErrorHandler();
        ErrorProcessor eProcessor = new ErrorProcessor();
        eProcessor.processError(fmsEH);
    }
}


NOW, what I really need is to have two args in my interface method ..
like:

public interface ErrorHandler {
   
    public void handleError(Object message, Throwable throwable);
   
}

and implement and use likewise ....

I can't make the connection for these arguments ???

Please advise !!!

Thanks much ...

_Esam.
0
 
LVL 11

Expert Comment

by:spoxox
ID: 20423233
1)
public class ErrorProcessor {
   
    public void processError(ErrorHandler eh){ // this wants to be FmsErrorHandler, not ErrorHandler
        eh.handleError();
    }
}
------- - - - - ------- - - - - ------- - - - - ------- - - - - ------- - - - - ------- - - - -
2)  NOW, what I really need is to have two args in my interface method ..
like:

public interface ErrorHandler {
   
    public void handleError(Object message, Throwable throwable);
   
}

OK, add the new handleError method to the ErrorHandler class, then implement it in FmsErrorHandler. As the signature is different from the existing handleError() method, you can do this.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 20423286
public void processError(ErrorHandler eh){
        eh.handleError();
    }

will have to process (pass) those arguments
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 92

Accepted Solution

by:
objects earned 150 total points
ID: 20423890
your ErrorProcessor class serves not purpose really, and you don't want to be passing an ErrorHandler around everywhere. Would be better written as:

public interface ErrorHandler {
   
    public void handleError(Object message, Throwable throwable);
   
}


public class ErrorProcessor {
    private ErrorHandler errorHandler;
    public class ErrorProcessor(ErrorHandler errorHandler) {
      this.errorHandler = errorHandler;
   }
   
    public void processError(Object message, Throwable throwable){
        errorHandler.handleError(message, throwable);
    }
}


public class FmsErrorHandler implements ErrorHandler{
   

    public void handleError(Object message, Throwable throwable){
     
        System.out.println(message);
          throwable.printStackTrace();
    }
}


public class TestErrorHandler {

    public static void main(String[] args) {
        FmsErrorHandler fmsEH = new FmsErrorHandler();
        ErrorProcessor eProcessor = new ErrorProcessor(fmsEH);
        eProcessor.processError("test", new Exception());
    }
}
0
 

Author Comment

by:_Esam
ID: 20424131
>>your ErrorProcessor class serves not purpose really,

Could you please let me know why this is?

Thanks.
_Esam..
0
 
LVL 92

Expert Comment

by:objects
ID: 20424163
because you could just call the error hqndler directly
0
 

Author Comment

by:_Esam
ID: 20424257
>>because you could just call the error hqndler directly

As CEHJ illustrated earlier like:
errorHandlerImplementer.handleError("This is the error for you!", new RuntimeException());

OR to say:

public class TestErrorHandler {

    public static void main(String[] args) {
        FmsErrorHandler fmsEH = new FmsErrorHandler();
        fmsEH.handleError("test", new Exception());
    }
}

Please let me know..

Thanks.
_Esam...
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 20424270
Yes, that's it
0
 
LVL 92

Expert Comment

by:objects
ID: 20424277
as i posted in my earlier cmment
0
 

Author Comment

by:_Esam
ID: 20424305
What purpose does the interface serve then ?

This is the million $ question then :)

I am trying to grasp this interface thing ...

I am trying to design to the interfaces not implementation...
How I accomplish it then ?

Thanks..
_Esam
0
 
LVL 92

Expert Comment

by:objects
ID: 20424324
you can still use your ErrorProcessor. Just the way you had it previously was redendant.
With the changesa I posted above it allows you to hide the ErrorHandler from your application code.
And allow you to add generic error handling to your processort, without having to add it to every error handler implementation
Otherwise theres no real point in having an interface at all :)

    public static void main(String[] args) {
        FmsErrorHandler fmsEH = new FmsErrorHandler();
        ErrorProcessor eProcessor = new ErrorProcessor(fmsEH);
        eProcessor.processError("test", new Exception());
    }
0
 
LVL 92

Expert Comment

by:objects
ID: 20424335
>What purpose does the interface serve then ?

if you wanted to have differnt error handler implementations, then you could just change the wiring of your processor
without changing any of your application code

eg.

    public static void main(String[] args) {
        ErrorHandler eh = new XyzErrorHandler();
        ErrorProcessor eProcessor = new ErrorProcessor(eh);
        eProcessor.processError("test", new Exception());
    }
0
 

Author Comment

by:_Esam
ID: 20424408
What I agree is that:
>>
if you wanted to have differnt error handler implementations, then you could just change the wiring of your processor
without changing any of your application code

eg.

    public static void main(String[] args) {
        ErrorHandler eh = new XyzErrorHandler();
        ErrorProcessor eProcessor = new ErrorProcessor(eh);
        eProcessor.processError("test", new Exception());
    }

<<
The purpose of the interface should be to allow multiple implementation ..
And the client shouldn't have to know the details of the implementation ...

If I am to invoke directly on the implementation,
Then my interface is just a dummy one....

I believe I should have the delegate .. ErrorProcessor ...

Or What would be the best approach to accomplish what I am trying to do ...
With the interface ?

Thanks much !
_Esam....
0
 
LVL 92

Expert Comment

by:objects
ID: 20424453
i'd use a deleagte, thatway you could also make it a singleton so you don't have to pass it around to every class that needs it (which is probably all of them)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 20424614
>>
If I am to invoke directly on the implementation,
Then my interface is just a dummy one....
>>

Not sure what the above means. One always invokes an implementation - it's not possible to do otherwise

What you'd normally do is use the reference to an interface, as opposed to an implementation. e.g.

Writer out = new FileWriter(f);
out.write(chars);

(An abstract class is functionally equivalent)
0
 
LVL 16

Assisted Solution

by:gnoon
gnoon earned 150 total points
ID: 20426518
>What purpose does the interface serve then ?
I think, the story begins at principal of "Java Inheritance and Polymorphism".

The rules are
- a class must inherit from a parent class (Object class by default).
- a class can inherit from many interfaces, and MUST implements all methods defined in those interfaces.

And I think, the most helpful of interface is to make sure that a class has the methods, which can be called from anywhere, defined in the interface.

For example

interface Inf1 {
  public void M1();
}

class Class1 implements Inf1 {
  public void M1() {
    System.out.println("Class1.M1()");
  }
  public void M2() {
    System.out.println("Class1.M2()");
  }
}

class Class2 extends Class1 {
  public void M() {
    System.out.println("Class2.M()");
  }
}

Class2 cls2 = new Class2();

cls2.M(); // just call to a known-method of Class2

if(cls instanceof Class1) { // test if it's subclass of Class1

  // At here, we know that we can call to the method M1() if we cast it back to Class1
  Class1 cls1 = (Class1) cls2;

  // then call to M1()
  cls1.M1();
}

Also this is equivalent

if(cls instanceof Inf1) { // test if it's subclass of Inf1
  Inf1 inf1 = (Inf1) cls2;
  inf1.M1();
}
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
mapAB Challlenge 35 128
mockito example issue 8 64
varialbe initialization 11 30
type mismatch (Object[] to double[] 4 13
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now