我试图创建一些 Java 类,其中包含一些共享方法,以及一些仅适用于其中某些类的其他方法(并且每个方法都应该是不同的)。
我做了一些研究,发现我可以使用 default
方法开发 Interface
,也可以使用 abstract 开发
方法。abstract
类
我的问题是,我想让这些未实现的方法在使用该类时不可用。我看到了这个 answer 但我认为为未实现的方法抛出 Exception
有点过分了。下面是我正在测试的代码。
可用方法:
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();
}
A类:
public class ClassA extends AvailableMethods {
@Override
public int methodTwo() {
return 123;
}
@Override
public String methodThree() {
return "test";
}
}
B类:
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
接口(interface)方法,但没有成功。我不确定这是否是一个层次结构问题(也许我应该实现不同的类并从其他类扩展限制方法可见性的类),但对我来说,不存在一种没有太多类/接口(interface)的方法来做到这一点似乎有点奇怪.
最佳答案
给你,我为你提供了一个小样本。
public class Example {
public static void main(){
ClassA a = new ClassA();
a.methodOne();
a.methodTwo();
a.methodThree();
ClassB b = new ClassB();
b.methodOne();
b.methodTwo();
}
}
interface One {
default void methodOne(){
System.out.println("Common method implementation");
}
}
abstract class Two implements One {
public abstract void methodTwo();
}
interface Three {
void methodThree();
}
class ClassA extends Two implements Three{
public void methodTwo() {}
@Override
public void methodThree() {}
}
class ClassB extends Two {
public void methodTwo() {}
}
关于java - 不实现抽象类中的方法(并使其不可访问),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55829114/