我试图创建一些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
接口方法但没有成功。我不确定它是否是一个层次结构的问题(也许我应该实现不同的类并从其他人那里扩展限制方法的可见性)但是如果没有太多的类/接口我没有现成的方法似乎有点奇怪。