Class 实现接口

Class implements Interface

所以我开始学习接口,现在我想知道什么时候使用

Interface i = new Class();

以及何时使用

Class c = new Class();

而且我注意到,如果我使用第一种方法,我不能使用 class 方法,只能使用接口方法。你知道为什么吗?

抱歉,我还是菜鸟 Java,感谢您的回答

OOP 范例中的接口用于概括一些相似对象组的共同行为。因此,您使用更通用类型的变量,例如接口你将只能使用接口定义的那些通用方法。由于您应该能够将任何接口后代(classes 实现给定接口)分配给接口变量,并且能够使用它。因此,当您分配

Interface i = new Class();

您将能够访问的唯一方法是 Interface 中定义的方法。另外需要注意的是,该变量将动态绑定到运行时类型,例如到您示例中的 Class,因此对您接口中定义的方法的调用将被分派到 class.

的实现

同时考虑以下内容,例如您有定义:

interface Vehicle {
     public void drive();
     public void stop();
}

现在如果你写代码:

Vehicle v = new BMW()
v.drive()
// do something else
v.stop()

当您将 new BMW() 替换为 new Mitsubishi() 时,它应该表现相同,而不管您的 BMW class 中可能有

class BMW {
    public void listenMusic()
}

这也叫“Liskov substitution principle

Liskov's notion of a behavioral subtype defines a notion of substitutability for objects; that is, if S is a subtype of T, then objects of type T in a program may be replaced with objects of type S without altering any of the desirable properties of that program.

让我简单地说一下。

接口定义了 class 的行为,实现接口的 classes 将提供该行为的实现。

这是一个例子

Interface Shape
{
 void draw();
}

Class Circle implements Shape
{
   void draw()
  {
    ... code to draw circle
  }

   void printRadius()
  {
  }
}

Class Rectangle implements Shape
{
   void draw()
  {
    ... code to draw rectangle
  }

   void printDiagonal()
  {
  }
}

现在,如果您看到相同的形状接口由 2 个 classes 不同地实现。

现在我可以这样写了

Shape shape = new Circle(); // This will allow you access only draw method
Circle circle = new Circle(); // This will allow you access all methods of circle

当您希望 client/consumer 仅访问特定于形状的方法(例如 draw)时,请使用 Shape shape = new Circle() 否则,如果您需要特定于圆的方法(例如 printRadius),则使用 Circle circle = new Circle()