Search code examples
javaclassinterfacevisibilityprotected

How to implement an interface on a protected java class


I was looking to implement an interface on a package-private java class, but I am having some difficulty achieving this. Below is an example.

class Foo
{
    String something(String str)
    {
        return ""str+"!";
    }
}




public interface Bar
{
    String something(String str);
}

What is the best approach here? My end goal is to implement the Bar interface on the Foo class. I am hoping to be able to cast Foo as Bar: (Bar)Foo

The Bar interface and the Foo class are in separate packages. Is there a way to do this?

Please advise.


Solution

  • You can't. The point of having the package level access it to precisely avoid seeing that class outside. What you can do however ( granted Foo is not final ) something like this:

    C:\>type *.java
    //Foo.java
    package foo;
    class Foo {
      String something( String s ) {
        return s + "!";
      }
    }  
    //Bar.java
    package bar;
    public interface Bar {
      public String something( String s );
    }    
    //Baz.java
    package foo;    
    import bar.Bar;    
    public class Baz extends Foo implements Bar {
      // make sure you're overriding
      @Override
      public String something ( String s ) {
        return super.something( s );
      }
    }     
    //Use it: Main.java
    package bar;
    import foo.Baz;   
    class Main {
      public static void main( String ... args ) {
        Bar bar = new Baz();
        System.out.println( bar.something("like this?"));
      }
    }
    
    C:\>java bar.Main
    like this?!
    

    Da da!

    The trick is to define the child in the same package as the parent so you can create a public version of it.

    I hope this helps.