简体   繁体   English

Java接口概念

[英]Java interface concept

When you build and interface, how many classes can implement the interface?构建和接口时,有多少个类可以实现接口?
If the answer is more than one, then how does java know which implementations to use when you make the call to the interface(not calling the implementation directly)?如果答案不止一个,那么当您调用接口(不直接调用实现)时,java如何知道要使用哪些实现?

how many classes can implement the interface?有多少个类可以实现接口?

As many as you need.你需要多少就多少。

If the answer is more than one, then how does java know which implementations to use when you make the call to the interface(not calling the implementation directly)?如果答案不止一个,那么当您调用接口(不直接调用实现)时,java如何知道要使用哪些实现?

Here helps knowledge about late binding (also known as dynamic binding).这里有助于了解后期绑定(也称为动态绑定)。

Lets say that you have interface and classes which implement it like假设您有实现它的接口和类

interface Animal{
    void makeSound();
}

class Cat implements Animal{
    public void makeSound(){
        System.out.println("mew");
    }
}

class Dog implements Animal{
    public void makeSound(){
        System.out.println("woof");
    }
}

You also have code like你也有类似的代码

Animal a1 = new Cat();
Animal a2 = new Dog();

a1.makeSound();
a2.makeSound();

Result which you will see is你会看到的结果是

mew
woof

It happens because body/code of method .makeSound() is being looked for (and invoked) at runtime (not compilation time).这是因为在运行时(不是编译时)正在查找(并调用)方法.makeSound()主体/代码 It is possible because each object remembers its class, so object held by a1 reference knows that it is instance of Cat and object held by a2 is instance of Dog .这是可能的,因为每个对象都会记住它的类,所以a1引用持有的对象知道它是Cat实例,而a2持有的对象是Dog实例。

So in short when you do:简而言之,当您这样做时:

a1.makeSound();
  • JVM takes object which a1 holds, JVM 获取a1持有的对象,
  • then asks that object about its class (in this case it will learn that it is instance of Cat class),然后询问该对象关于它的类(在这种情况下它会知道它是Cat类的实例),
  • then it will accesses that class ( Cat.class file) and is searching for code of makeSound() (if such method will not be found, then it will assume it must been inherited it will try to search it in superclass)然后它将访问该类( Cat.class文件)并搜索makeSound()代码(如果找不到这样的方法,那么它将假定它必须被继承,它将尝试在超类中搜索它)
  • and when it will find this method it will invoke code from it.当它找到这个方法时,它会从中调用代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM