Java 接口的部分实现
我只有一小部分时间来搜索这些东西,所以我看不到任何涉及我特定场景的内容 我正在使用第三方界面。让我们先说一下:Java 接口的部分实现,java,Java,我只有一小部分时间来搜索这些东西,所以我看不到任何涉及我特定场景的内容 我正在使用第三方界面。让我们先说一下: public interface interface1 { public String getVar1(); public void method1(); public void method2(); } 我需要创建一些使用此接口的类,但是“method2”的实际方法实现在每个类上都不同,其中as“met
public interface interface1
{
public String getVar1();
public void method1();
public void method2();
}
我需要创建一些使用此接口的类,但是“method2”的实际方法实现在每个类上都不同,其中as“method1”和“getVar1”始终是相同的代码
有没有办法创建一个抽象基类来实现接口,但只强制子类实现“method2”
我试过了
public abstract @Override void method2
但是,尽管在Netbeans中,在设计时这是“可接受的”(不知道Eclipse的行为是否不同),但在编译时,它抱怨需要实现method2
如果不可能,公平地说,我只需要检查一下
谢谢您可以通过创建一个实现接口的抽象类来实现这一点。这个抽象类的任何子类都需要实现任何尚未定义的接口方法
public abstract class AbstractInterface implements interface1 {
@Override
public String getVar1() {
}
@Override
public void method1() {
}
}
请参阅:.您可以拥有一个
抽象类
,该类提供“方法1”和“getVar1”的实现,但将decare方法2作为抽象类
现在在所有其他类中继承这个抽象的超类
像
您可以创建一个不实现
method2()
然后创建多个实现:
public class Implementation1 extends AbstractImplementation {
public void method2() {
// implementation 1
}
}
public class Implementation2 extends AbstractImplementation {
public void method2() {
// implementation 2
}
}
...
在这种情况下,接口中有3个抽象方法,您可以重写一个或两个方法,其他方法将保持为抽象
abstact class PartialImplementationDemo implements interface1 {
@Override
public void method1() {
// override method1() here
}
// leave other methods as abstract
abstract public void method2();
abstract public String getVar1();
}
你需要声明你的类抽象并省略
method2的任何实现
对于Kotlin
,这里有同样的问题:他在谈论第三方接口。如果第三方程序中的代码无效(interface1 test){test.getVar1();//无法调用此服务}Ups,我忘记添加实现接口1
。更正了这个。感谢您的信息输出:在方法1中的方法2中的方法3中,请编辑您的答案并添加一些有关如何应用此代码的信息。
public abstract class AbstractImplementation implements interface1 {
public String getVar1() {
// implementation ..
}
public void method1() {
// implementation ..
}
// skip method2
}
public class Implementation1 extends AbstractImplementation {
public void method2() {
// implementation 1
}
}
public class Implementation2 extends AbstractImplementation {
public void method2() {
// implementation 2
}
}
...
abstact class PartialImplementationDemo implements interface1 {
@Override
public void method1() {
// override method1() here
}
// leave other methods as abstract
abstract public void method2();
abstract public String getVar1();
}
interface I1
{
public void Method1();
public void Method2();
}
abstract class A implements I1
{
public void Method1()
{
System.out.println("In Method 1");
}
abstract public void Method3();
}
class B extends A //Inherits class A
{
public void Method2()
{
System.out.println("In Method 2");
}
public void Method3()
{
System.out.println("In Method 3");
}
}
public class Main
{
public static void main(String args[])
{
B b1=new B();
b1.Method1();
b1.Method2();
b1.Method3();
}
}