skip skip - 2 months ago 6
Java Question

How to extend an interface

I am coding to interface.

I have an interface A and a class B that implements it.

I am told that I could override B's functionalities by extending it by C but I am asked to touch neither B nor C, and then later replace B with C as the implementation class of A in the configuration files.

I figure that I need a method that is not available in A, so I need to add a method to A that I could implement in C. But I am not allowed to touch A.

Could someone help me with how-could-it-be done?


Example code:

public interface A {
void X();
void Y();

public class B implements A {
public void X() {//something interesting}
public void Y() {//something not very interesting}

Now because I was not allowed to touch either
I had to write another class
and extend it from B to do my things.

public class C extends B {
public void Y() {//overriding B's not very interesting Y and making it interesting}

Now I need another method
void Z()
in to do my thing but because I am coding to interface
if I add a method just on while using
reference variable I will not be able to call
so I will have to declare
void Z()
interface as well to use it like that but if I do that I will have to touch
which I am not allowed to. So how to get this issue resolved is what I've been trying to ask.

So essentially, I wont be able to do something like following:

A a = new C();
a.Z(); //can't do this

So is there any way for me to achieve something like that without touching A or B?


I think I understand what you want. You have the following:

public interface A {
  // can't touch this

public class B implements A {
  // can't touch this

public class C extends B {
  // you want to add your own method
  void someNewMethod();

// And you wish to do this:
A foo = new C();

If this is what you want, then I'm afraid it cannot be done. Anyone working with A only knows about the methods defined in A; they won't know you've defined someNewMethod() in your class C. You need to be allowed to change A.

Note that in extremis, you could check the class type of instances of A:

A foo;
// ...

if (foo instanceof C) {
  ((C) foo).someNewMethod();

but that is really ugly and breaks many of the cardinal rules of OO programming.