tags:

views:

44

answers:

4

I have a use case of this kind

interface i {
   void method1();
   void method2();
}

class A implements i {
  void method1() {
     System.out.println("Method1 A ..");
  }

  void method2() {
     System.out.println("Method2 A ..");
  }
}


class B implements i {

  void method1() {
     System.out.println("Method1 B ..");
  }

  //Assume : B does not know how to implement method2
  //void method2() {

  //}
}

I know class B can be abstract and not implement method2 for interface i. Is the general practice that if I don't want my class B to be abstract to throw exception from method2 if it does not have any implementation for method2.

+2  A: 

If you are not going to implement a method from an interface you can throw an UnsupportedOperationException. Really though this situation should be avoided if possible, maybe rethink the design.

Alb
You mean java.lang.UnsupportedOperationException ?
DJClayworth
@DJClayworth yes of course, thanks :)
Alb
+1  A: 

If B does not know how to implement method2, then your interface is kind of wrong. You would need a more generalized interface, without method2, and perhaps an extending interface which contains method to, but which is not implemented by B.

x3ro
There can be the case where you do not own the interface though and have no control over it.
Alb
+4  A: 

If you are not fully implementing all required methods of an interface, you should not be implementing that interface. It appears that what you are actually trying to do is this:


interface top
{
   void method1(); 
}

interface next extends top
{
    void method2();
}

class A implements next
{
    public void method1()
    {
        ... something ...
    }

    public void method2()
    {
        ... something ...
    }
}

class B implements top
{
    public void method1()
    {
        ... something ...
    }
}

dwb
A: 

There are some precendents for this in the standard Java libraries. Some of the most notable are the "remove" method from the Iterator interface, which throws UnsupportedOperationException. Remember to document the interface to say that throwing this exception is allowable.

DJClayworth