Java 中的接口:无法将实现的方法设置为受保护或私有

发布于 2024-07-11 14:06:47 字数 182 浏览 15 评论 0原文

我知道接口必须是公共的。 然而,我不想要这样。

我希望我实现的方法只能从它们自己的包中访问,所以我希望我实现的方法受到保护。

问题是我无法保护接口或实现的方法。

什么是解决办法? 有没有与这个问题相关的设计模式?

根据 Java 指南,抽象类也无法完成这项工作。

I know that an interface must be public. However, I don't want that.

I want my implemented methods to only be accessible from their own package, so I want my implemented methods to be protected.

The problem is I can't make the interface or the implemented methods protected.

What is a work around? Is there a design pattern that pertains to this problem?

From the Java guide, an abstract class wouldn't do the job either.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

吻安 2024-07-18 14:06:47

阅读

“公共访问说明符表明该接口可以被任何包中的任何类使用。如果您没有指定该接口是公共的,则您的接口将只能被与该接口在同一包中定义的类访问< /强>。”

那是你要的吗?

read this.

"The public access specifier indicates that the interface can be used by any class in any package. If you do not specify that the interface is public, your interface will be accessible only to classes defined in the same package as the interface."

Is that what you want?

烟柳画桥 2024-07-18 14:06:47

您的类可以使用包保护并仍然实现一个接口:

class Foo implements Runnable 
{
    public void run()
    {
    }
}

如果您希望某些方法受到保护/包而其他方法则不受到保护/包,那么听起来您的类有多个职责,并且应该分为多个。

阅读对此回复和其他回复的评论后进行编辑:

如果您以某种方式认为方法的可见性会影响调用该方法的能力,请再考虑一下。 如果不走极端,您就无法阻止某人使用反射来识别您的类的方法并调用它们。 然而,这不是问题:除非有人试图破解您的代码,否则他们不会调用随机方法。

相反,将私有/受保护方法视为定义子类的契约,并使用接口来定义与外界的契约。

哦,对于决定我的示例应该使用 K&R 支撑的人:如果服务条款中指定,当然可以。 否则,你就不能找到更好的事情来打发你的时间吗?

You class can use package protection and still implement an interface:

class Foo implements Runnable 
{
    public void run()
    {
    }
}

If you want some methods to be protected / package and others not, it sounds like your classes have more than one responsibility, and should be split into multiple.

Edit after reading comments to this and other responses:

If your are somehow thinking that the visibility of a method affects the ability to invoke that method, think again. Without going to extremes, you cannot prevent someone from using reflection to identify your class' methods and invoke them. However, this is a non-issue: unless someone is trying to crack your code, they're not going to invoke random methods.

Instead, think of private / protected methods as defining a contract for subclasses, and use interfaces to define the contract with the outside world.

Oh, and to the person who decided my example should use K&R bracing: if it's specified in the Terms of Service, sure. Otherwise, can't you find anything better to do with your time?

嗼ふ静 2024-07-18 14:06:47

当我遇到这个问题时,我使用包可访问的内部或嵌套类来实现接口,将实现的方法从公共类中推出。

通常是因为我有一个具有特定公共 API 的类,它必须实现其他东西才能完成它的工作(通常是因为其他东西是伪装成接口的回调) - 这种情况在 Comparable 之类的事情上经常发生。 我不希望公共 API 被(强制公共)接口实现所污染。

希望这可以帮助。

另外,如果您确实想要仅由包访问的方法,则不需要 protected 范围说明符,您需要默认(省略)范围说明符。 当然,使用 protected 将允许子类看到这些方法。

顺便说一句,我认为接口方法被推断为公共的原因是因为拥有一个仅由同一包中的类实现的接口是非常例外的; 它们最常被另一个包中的某些东西调用,这意味着它们需要公开。

When I have butted up against this I use a package accessible inner or nested class to implement the interface, pushing the implemented method out of the public class.

Usually it's because I have a class with a specific public API which must implement something else to get it's job done (quite often because the something else was a callback disguised as an interface <grin>) - this happens a lot with things like Comparable. I don't want the public API polluted with the (forced public) interface implementation.

Hope this helps.

Also, if you truly want the methods accessed only by the package, you don't want the protected scope specifier, you want the default (omitted) scope specifier. Using protected will, of course, allow subclasses to see the methods.

BTW, I think that the reason interface methods are inferred to be public is because it is very much the exception to have an interface which is only implemented by classes in the same package; they are very much most often invoked by something in another package, which means they need to be public.

帅的被狗咬 2024-07-18 14:06:47

这个问题是基于一个错误的陈述:

我知道接口必须是公共的

事实并非如此,您可以拥有带有默认访问修饰符的接口。

问题是我无法使接口或实现的方法受到保护

这里是:

C:\oreyes\cosas\java\interfaces>type a\*.java
a\Inter.java
package a;

interface Inter {
    public void face();
}

a\Face.java
package a;

class Face implements Inter {
    public void face() {
        System.out.println( "face" );
    }
}


C:\oreyes\cosas\java\interfaces>type b\*.java
b\Test.java

package b;
import a.Inter;
import a.Face;

public class Test {
    public static void main( String [] args ) {
        Inter inter = new Face();
        inter.face();
    }
}

C:\oreyes\cosas\java\interfaces>javac -d . a\*.java b\Test.java
b\Test.java:2: a.Inter is not public in a; cannot be accessed from outside package
import a.Inter;
        ^
b\Test.java:3: a.Face is not public in a; cannot be accessed from outside package
import a.Face;
        ^
b\Test.java:7: cannot find symbol
symbol  : class Inter
location: class b.Test
        Inter inter = new Face();
        ^
b\Test.java:7: cannot find symbol
symbol  : class Face
location: class b.Test
        Inter inter = new Face();
                          ^
4 errors

C:\oreyes\cosas\java\interfaces>

因此,实现你想要的,防止在包之外使用接口和类。

This question is based on a wrong statement:

I know that an interface must be public

Not really, you can have interfaces with default access modifier.

The problem is I can't make the interface or the implemented methods protected

Here it is:

C:\oreyes\cosas\java\interfaces>type a\*.java
a\Inter.java
package a;

interface Inter {
    public void face();
}

a\Face.java
package a;

class Face implements Inter {
    public void face() {
        System.out.println( "face" );
    }
}


C:\oreyes\cosas\java\interfaces>type b\*.java
b\Test.java

package b;
import a.Inter;
import a.Face;

public class Test {
    public static void main( String [] args ) {
        Inter inter = new Face();
        inter.face();
    }
}

C:\oreyes\cosas\java\interfaces>javac -d . a\*.java b\Test.java
b\Test.java:2: a.Inter is not public in a; cannot be accessed from outside package
import a.Inter;
        ^
b\Test.java:3: a.Face is not public in a; cannot be accessed from outside package
import a.Face;
        ^
b\Test.java:7: cannot find symbol
symbol  : class Inter
location: class b.Test
        Inter inter = new Face();
        ^
b\Test.java:7: cannot find symbol
symbol  : class Face
location: class b.Test
        Inter inter = new Face();
                          ^
4 errors

C:\oreyes\cosas\java\interfaces>

Hence, achieving what you wanted, prevent interface and class usage outside of the package.

︶ ̄淡然 2024-07-18 14:06:47

以下是如何使用抽象类来完成此操作。

唯一不方便的是它使你成为“子类”。

根据 java 指南,您应该“大多数”时候遵循该建议,但我认为在这种情况下就可以了。

public abstract class Ab { 
    protected abstract void method();
    abstract void otherMethod();
    public static void main( String [] args ) { 
        Ab a = new AbImpl();
        a.method();
        a.otherMethod();
    }
}
class AbImpl extends Ab {
    protected void method(){
        System.out.println( "method invoked from: " + this.getClass().getName() );
    }
    void otherMethod(){ 
        System.out.println("This time \"default\" access from: " + this.getClass().getName()  );
    }
}

Here's how it could be done using abstract classes.

The only inconvenient is that it makes you "subclass".

As per the java guide, you should follow that advice "most" of the times, but I think in this situation it will be ok.

public abstract class Ab { 
    protected abstract void method();
    abstract void otherMethod();
    public static void main( String [] args ) { 
        Ab a = new AbImpl();
        a.method();
        a.otherMethod();
    }
}
class AbImpl extends Ab {
    protected void method(){
        System.out.println( "method invoked from: " + this.getClass().getName() );
    }
    void otherMethod(){ 
        System.out.println("This time \"default\" access from: " + this.getClass().getName()  );
    }
}
辞慾 2024-07-18 14:06:47

这是另一个解决方案,其灵感来自于 C++ Pimpl 习惯用法。

如果您想要实现一个接口,但不希望该实现是公共的,则可以创建一个实现该接口的匿名内部类的组合对象。

这是一个例子。 假设您有这个接口:

public interface Iface {
    public void doSomething();
}

您创建一个 Iface 类型的对象,并将实现放入其中:

public class IfaceUser {
    private int someValue;
    // Here's our implementor
    private Iface impl = new Iface() {
        public void doSomething() {
            someValue++;
        }
    };
}

每当您需要调用 doSomething() 时,您就可以在您的组合 impl 对象。

Here's another solution, inspired by the C++ Pimpl idiom.

If you want to implement an interface, but don't want that implementation to be public, you can create a composed object of an anonymous inner class that implements the interface.

Here's an example. Let's say you have this interface:

public interface Iface {
    public void doSomething();
}

You create an object of the Iface type, and put your implementation in there:

public class IfaceUser {
    private int someValue;
    // Here's our implementor
    private Iface impl = new Iface() {
        public void doSomething() {
            someValue++;
        }
    };
}

Whenever you need to invoke doSomething(), you invoke it on your composed impl object.

世俗缘 2024-07-18 14:06:47

我刚刚遇到这个问题,试图构建一个受保护的方法,其目的是仅在测试用例中使用它。 我想删除填充到数据库表中的测试数据。 无论如何,我的灵感来自 @Karl Giesing帖子。 不幸的是它没有起作用。 我确实找到了一种使用受保护的内部类使其工作的方法。

接口:

package foo;
interface SomeProtectedFoo {
    int doSomeFoo();
}

然后在公共类中定义为受保护的内部类:

package foo;
public class MyFoo implements SomePublicFoo {
    // public stuff
    protected class ProtectedFoo implements SomeProtectedFoo {
        public int doSomeFoo() { ... }
    }
    protected ProtectedFoo pFoo;
    protected ProtectedFoo gimmeFoo() {
        return new ProtectedFoo();
    }
}

然后您只能从同一包中的其他类访问受保护的方法,正如我的测试代码所示:

package foo;
public class FooTest {
    MyFoo myFoo = new MyFoo();
    void doProtectedFoo() {
        myFoo.pFoo = myFoo.gimmeFoo();
        myFoo.pFoo.doSomeFoo();
    }
}

对于原始海报来说有点晚了,但是嘿,我刚刚找到了。 :D

I just came across this trying to build a protected method with the intention of it only being used in a test case. I wanted to delete test data that I had stuffed into a DB table. In any case I was inspired by @Karl Giesing's post. Unfortunately it did not work. I did figure a way to make it work using a protected inner class.

The interface:

package foo;
interface SomeProtectedFoo {
    int doSomeFoo();
}

Then the inner class defined as protected in public class:

package foo;
public class MyFoo implements SomePublicFoo {
    // public stuff
    protected class ProtectedFoo implements SomeProtectedFoo {
        public int doSomeFoo() { ... }
    }
    protected ProtectedFoo pFoo;
    protected ProtectedFoo gimmeFoo() {
        return new ProtectedFoo();
    }
}

You can then access the protected method only from other classes in the same package, as my test code was as show:

package foo;
public class FooTest {
    MyFoo myFoo = new MyFoo();
    void doProtectedFoo() {
        myFoo.pFoo = myFoo.gimmeFoo();
        myFoo.pFoo.doSomeFoo();
    }
}

A little late for the original poster, but hey, I just found it. :D

春花秋月 2024-07-18 14:06:47

您可以使用封装而不是继承。

也就是说,创建您的类(不会继承任何内容)并在其中包含您要扩展的对象的实例。

然后你就可以只公开你想要的内容。

这样做的明显缺点是您必须显式传递您想要公开的所有内容的方法。 而且它不会是一个子类......

You can go with encapsulation instead of inheritance.

That is, create your class (which won't inherit anything) and in it, have an instance of the object you want to extend.

Then you can expose only what you want.

The obvious disadvantage of this is that you must explicitly pass-through methods for everything you want exposed. And it won't be a subclass...

旧夏天 2024-07-18 14:06:47

我只想创建一个抽象类。 这没有什么坏处。

I would just create an abstract class. There is no harm in it.

弃爱 2024-07-18 14:06:47

对于接口,您希望定义可以由各种实现类公开的方法。
拥有一个带有受保护方法的接口并不能达到这个目的。

我猜你的问题可以通过重新设计你的类层次结构来解决。

With an interface you want to define methods that can be exposed by a variety of implementing classes.
Having an interface with protected methods just wouldn't serve that purpose.

I am guessing your problem can be solved by redesigning your class hierarchy.

烟─花易冷 2024-07-18 14:06:47

解决这个问题的一种方法是(根据情况)创建一个匿名内部类来实现具有受保护或私有范围的接口。 例如:

public class Foo {
    interface Callback {
        void hiddenMethod();
    }

    public Foo(Callback callback) {
    }
}

然后在 Foo 的用户中:

public class Bar {
    private Foo.Callback callback = new Foo.Callback() { 
        @Override public void hiddenMethod() { ... }
    };
    private Foo foo = new Foo(callback);
}

这可以让您避免出现以下情况:

public class Bar implements Foo.Callback {
    private Foo foo = new Foo(this);

    // uh-oh! the method is public!
    @Override public void hiddenMethod() { ... }
}

One way to get around this is (depending on the situation) to just make an anonymous inner class that implements the interface that has protected or private scope. For example:

public class Foo {
    interface Callback {
        void hiddenMethod();
    }

    public Foo(Callback callback) {
    }
}

Then in the user of Foo:

public class Bar {
    private Foo.Callback callback = new Foo.Callback() { 
        @Override public void hiddenMethod() { ... }
    };
    private Foo foo = new Foo(callback);
}

This saves you from having the following:

public class Bar implements Foo.Callback {
    private Foo foo = new Foo(this);

    // uh-oh! the method is public!
    @Override public void hiddenMethod() { ... }
}
擦肩而过的背影 2024-07-18 14:06:47

我想你现在可以在 Java 9 版本中使用它。 来自 Java 9 的 openJDK 注释,

简要考虑了对接口中私有方法的支持
作为添加支持的一部分,包含在 Java SE 8 中
Lambda 表达式,但被撤回以更好地关注更高的
Java SE 8 的优先任务。现在建议支持
采取私有接口方法,从而实现非抽象
接口的方法以在它们之间共享代码。

参考 https://bugs.openjdk.java.net/browse/JDK-8071453

I think u can use it now with Java 9 release. From the openJdk notes for Java 9,

Support for private methods in interfaces was briefly in consideration
for inclusion in Java SE 8 as part of the effort to add support for
Lambda Expressions, but was withdrawn to enable better focus on higher
priority tasks for Java SE 8. It is now proposed that support for
private interface methods be undertaken thereby enabling non abstract
methods of an interface to share code between them.

refer https://bugs.openjdk.java.net/browse/JDK-8071453

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文