不从抽象类实现方法(并使其不可访问)

问题描述 投票:0回答:1

我试图创建一些Java类,其中包含一些共享方法,并且其他一些方法仅适用于其中一些类(并且每个方法都应该是不同的)。

我做了一些研究,我发现我可以用Interface方法开发default或用abstract方法开发abstract类。

我的问题是,我想在使用该类时使这些未实现的方法不可用。我看到了这个answer,但我认为为未实现的方法抛出一个Exception有点过分。以下是我正在测试的代码。

AvailableMethods:

public abstract class AvailableMethods {

    // This is the shared method
    void methodOne(){
        System.out.println("Common method implementation");
    }

    // This should always be implemented and have always different logic
    abstract int methodTwo();

    /* This should be only implemented in some cases and when not 
       implemented it should not be visible while using the class */
    abstract String methodThree();

}

ClassA的:

public class ClassA extends AvailableMethods {

    @Override
    public int methodTwo() {
        return 123;
    }

    @Override
    public String methodThree() {
        return "test";
    }
}

ClassB的:

public class ClassB extends AvailableMethods {
    @Override
    public int methodTwo() {
        return 456;
    }

    // I was trying to get rid of this implementation without defining a default value
    @Override
    public String methodThree() {
        return null;
    }
}

测试:

public class Test {

    public static void main(String[] args){
        ClassA a = new ClassA();
        ClassB b = new ClassB();

        b.methodOne();
        b.methodTwo();
    }

}

基本上我想要实现的是在我的IDE中键入b.methodThree没有被建议/可用。

我不知道是否可能。我也尝试过使用default接口方法但没有成功。我不确定它是否是一个层次结构的问题(也许我应该实现不同的类并从其他人那里扩展限制方法的可见性)但是如果没有太多的类/接口我没有现成的方法似乎有点奇怪。

java interface abstract-class default visibility
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.