2

朋友们,我在 Java 中遇到了一个问题:我想实现一个结构,但我在做这件事时遇到了一些困难,谁能帮助我。

interface samp1{
    method1()
    method2()
    method3()
}

interface samp2{
    method4()
    method5()
}
class Samp implements samp1,samp2
{
  // this class needs only method1 from interface samp1 and method 4 from interface samp2
  // I don't want to override all the methods from interface 
}

任何人都可以为此提出一些解决方案吗?

有没有可用的设计模式?如果是这样,请提供参考链接。

提前致谢。

4

6 回答 6

10

一个接口就是一个契约。它说“我的班级实现了所有这些方法”。

请参阅:http ://docs.oracle.com/javase/tutorial/java/concepts/interface.html

如果您不希望那样,请不要使用接口。

于 2013-01-19T18:37:08.263 回答
2

Java 8 allows default methods in an interface, that are used if the particular method is not overridden when the interface is implemented. For example:

interface MyInterface{
    //if a default method is not provided, you have to override it 
    public int Method1(); 
    public default int Method2(){
        return 2;
    }
}

public class MyClass{
    public static void main(String args[]){
        MyInterface in = new MyInterface(){
            public int Method1(){
                return 0;
            }
        };
        //uses the implemented method
        System.out.println(in.Method1()); //prints 0
        //uses the default method
        System.out.println(in.Method2()); // prints 2
    }
}
于 2017-01-03T16:22:55.243 回答
1

实现接口时,除了实现接口中的所有方法之外别无他法。在上面的“samp”类中,您正在实现“samp1”和“samp2”接口,因此您必须在 samp 类中实现 samp1 和 samp2 中的所有方法。

你说从接口覆盖方法。您不会覆盖接口中的方法,您只需实现方法。

您可以使用抽象类来解决您的问题。

abstract class AbstractSamp implement samp1,samp2{

 method1(){...}
 method4(){...}
}

您可以在您的 samp 类中扩展 Abstractsamp,如下所示

class samp extends AbstractSamp{

// here you can extend method1() and method4() by inheritence and you can also    override   them as you want

}
于 2013-01-19T19:02:54.617 回答
0

如果没有更多关于您要实现的目标的背景信息,我建议您这样做:

interface BaseSamp {
    void method1();
    void method4();
}

interface Samp1 extends BaseSamp {
     void method2();
     void method3();
}

interface Samp2 extends BaseSamp {
    void method5();
}

class YourClass implements BaseSamp {
 ....
}
于 2013-01-19T18:36:30.527 回答
0
interface MySpecializedInterface{
   public void method1();
   public void method4();
}

class YourClass implements MySpecializedInterface{

  // now you can implement method1 and method4... :|
}
于 2013-01-19T18:40:25.987 回答
0

将类声明为abstract,您将不需要实现所有方法。但是,请注意抽象类不能被实例化。

于 2013-01-19T18:34:44.470 回答