Solved

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

Posted on 2007-12-06
28
257 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
Comment Utility
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
Comment Utility
(The other message should be there too or it won't compile)
0
 
LVL 24

Expert Comment

by:sciuriware
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
You call the class that implements the interface with them
0
 

Author Comment

by:_Esam
Comment Utility
Exactly . how so ?
0
 
LVL 86

Expert Comment

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

Author Comment

by:_Esam
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
public void processError(ErrorHandler eh){
        eh.handleError();
    }

will have to process (pass) those arguments
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 92

Accepted Solution

by:
objects earned 150 total points
Comment Utility
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
Comment Utility
>>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
Comment Utility
because you could just call the error hqndler directly
0
 

Author Comment

by:_Esam
Comment Utility
>>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
Comment Utility
Yes, that's it
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
as i posted in my earlier cmment
0
 

Author Comment

by:_Esam
Comment Utility
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
Comment Utility
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
Comment Utility
>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
Comment Utility
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
Comment Utility
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
Comment Utility
>>
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
Comment Utility
>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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Fibonacci challenge 11 81
json format text only 4 64
word0 challenge 4 52
Image decoding from Camera 3 42
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This video teaches viewers about errors in exception handling.

763 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

9 Experts available now in Live!

Get 1:1 Help Now