【问题标题】:How can i make my own interface with methods from other class? [closed]如何使用其他类的方法创建自己的接口? [关闭]
【发布时间】:2014-03-27 19:55:53
【问题描述】:

我需要创建一个接口,该接口将声明来自 File 类的方法 + 我的一些方法。 我怎样才能实现我的接口,所以从 File 类方法中获取的所有方法都与在 File 类中的方法相同? my task 我不知道该怎么做

【问题讨论】:

  • 你不能。但是,您可以扩展 File
  • public myClass extends myBaseClass{ //TODO }
  • 不知道为什么你会被否决。我认为这是一个有效的问题。
  • 您能更具体地说明您想要实现的目标吗?您打算如何使用该界面?
  • @CostiCiudatu 请查看添加的任务

标签: java interface


【解决方案1】:

您可以声明自己的接口:

public interface MyInterface {
    void myMethod();
}

然后声明你自己的类扩展 File 并实现你的接口:

public class MyFile extends File implements MyInterface {

    public MyFile(String pathname) {
        super(pathname);
        // Additional constructor code.
    }

    @Override
    public void myMethod() {
        // Overridden method from MyInterface.
        System.out.println("My method!");
    }

    @Override
    public String getName() {
        // Overridden method from File.
        return "MyFileName";
    }
}

这样,您就有了一个类似于 File 的类,其中包含来自您的自定义接口的其他方法,并且您可以从 File 覆盖您想要的方法。

使用示例:

MyInterface customFile = new MyFile("myFile.txt");
customFile.myMethod();

【讨论】:

  • 问题暗示接口需要声明File类的所有公共方法,所以我想你应该相应地增强MyInterface
  • 我可以通过这种方式创建基于 Myinterface 的对象吗?
  • @CostiCiudatu File 有很多方法,所以老实说,我认为从它扩展并覆盖你想要以不同方式操作的方法比用 all填充接口更好> File 的方法。 MyInterface 仅适用于不属于File 的附加行为。
  • @Cupuycblack 是的,完全是。请参阅我的答案中添加的示例。
  • 我的疯狂猜测(因为这个问题几乎没有提供任何提示)是该接口应该像这样使用:MyInterface ref = ...; ref.getAbsoluteFile(); ref.toURL(); ref.myMethod(); ...。但我可能错了;无论如何,你有我的赞成票。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-13
  • 2021-06-23
  • 1970-01-01
  • 1970-01-01
  • 2011-07-13
  • 1970-01-01
相关资源
最近更新 更多