为什么不能在接口类型上引用类的方法

时间:2018-01-21 06:01:07

标签: java interface

为什么我们不能在实现该接口的接口类型上调用类方法..?有什么问题?

...
dev: {
  ...
  proxyTable: {
    '/t/*.*': { // this will match all urls with dots after '/t/'
      target: 'http://localhost:8080/',  // send to webpack dev server
      router: function (req) {
        req.url = 'index.html'  // Send to vue app
      }
    }
    // Any other routes you need to bypass should go here.
  }
  ...
},
...

如果Interface类型可以引用类对象,那为什么他不能访问类方法?因为最后,该调用仅适用于类的对象..没有..?

4 个答案:

答案 0 :(得分:3)

尝试

Class O = new Class(); or `((Class)O).classmethod(); If you are using Interface O = new Class();` 

您可以访问所有方法。

     Interface O = new Class(); 

这称为动态调度。通过此,您只能访问界面中的那些方法。不是实现接口方法的Class的独有属性的其他方法。

在您的示例中,您的接口有方法:void Iaminterfacemethod();实现它的类具有另一个不在接口中的方法,即void classmethod() Interface O = new Class();可以O.Iaminterfacemethod();但是O.classmethod();不是。为此,您需要Class O = new Class();现在O.classmethod();O.Iaminterfacemethod();都可以。

答案 1 :(得分:3)

编写代码并编译运行时会发生两件事。

  1. 在编译时编译器检查您是否具有正确的语法和方法/变量可访问性检查。
  2. 现在,在运行时对象将被创建并执行强制转换和/或装箱(在需要的地方)。
  3. 写作时

    <Interface> O = new <Class>();
    O.classmethod();  <-- will be checked at compile time
    

    因此,基本上编译器会检查classmethod O是否存在<Interface>,这是<Interface>

    现在,假设classmethod已由多个类实现,<Class>方法被不同的行为覆盖。然后,根据<Interface>(实现MapKit)的对象,该方法将在运行时动态绑定。

答案 2 :(得分:0)

这是继承的工作原理。

Interface O = new Class();

这里O是接口的引用,因此O只知道接口中定义的方法。

您只能参考参考知道的方法。

答案 3 :(得分:0)

在您的子类或实现类中声明的方法不是超类/接口的一部分,因此您不能调用那些在超类/接口引用类型的子类中声明的方法。编译器会检查引用变量o是否有方法classmethod(),它不会。

相关问题