Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to limit access to a method of a public interface?

user8478974Dec 26 2007 — edited Jul 4 2008
I have the following problem:

I want to have an interface, which is public, but has one method that I want to be protected. In the example below, methodB() is the method that I want protected. If I declare it as protected, the compiler complains. So I leave it without any decorations, as shown below.
public interface MyInterface {

    public int methodA();

    void methodB();

} 
Now, suppose I want to have a class that implements MyInterface. I try the following:
public class MyClass implements MyInterface {

    public int methodA() {
        return 42;
    }

    void methodB() {
        System.out.println("This is my secret.");
    }
}
The compiler complains again, saying that I am "attempting to assign weaker access privileges; was public". I seem to have no other choice than declare methodB in class MyClass as public.

My first question is: Please explain the logic here.

I want methodB to be declared in MyInterface, so that I may call within my own package:
o.methodB()
on any object o of type MyInterface, without having to cast it to a concrete class (that's the beauty of polymorphism).

My second question is: What shall I do?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 1 2008
Added on Dec 26 2007
31 comments
2,765 views