为什么Java的接口不能定义构造函数?
巴扎黑
巴扎黑 2017-04-18 09:55:22
0
12
1156

为什么Java的接口不能定义构造函数?

巴扎黑
巴扎黑

reply all(12)
伊谢尔伦
非要逼死抽象类不可!
大家讲道理

First of all, you must understand the role of the constructor. The constructor is to initialize the attributes or methods of the class. It is automatically called at the moment of new. Then the problem is that the interfaces of Java and PHP cannot be new. So why do we need a constructor? There is no way to call it at all

巴扎黑

Why is the king’s three horizontal and one vertical?

伊谢尔伦

Interfaces define behavior, not production methods

小葫芦

How do you instantiate it?

左手右手慢动作

Because the interface will not have its own instance, there is no need for a constructor.

Why doesn’t an interface have its own instance? Because the interface only defines a series of abstract functions, when using the interface, you will use the class that implements the interface, and you will not use the interface directly. Use it directly, those functions are just definitions and cannot be used

Of course, in Java 8, functions defined by interfaces can have default implementations, but you still cannot directly use the interface to call such functions.

阿神

Interface cannot be instantiated. If it can be new, what is the point of having an interface? However, after Java 8, interfaces can have default methods, which can be called directly

伊谢尔伦

Hey...the simpler the question, the harder it is to answer. I can only say that when the Java language was designed, the interface was defined as a specification that a class needs to follow. It was designed to make up for the shortcomings of single inheritance. There is a book "Programmer's Cry" in which the author criticizes the design of Java interfaces and writes: "Goslin said that if the Java language is rewritten, interfaces will not be considered."

巴扎黑

Abstract classes are OK. An interface cannot define method details, only a series of its behaviors.

伊谢尔伦

I tentatively think that the questioner wants to use the constructor in the interface because he wants to do some code reuse in the class that specifically implements the interface.

interface I {
  public I() {
    system.out.println("不管你怎么实现,我最牛逼");
  }
}

There are some conflicts between "code reuse" and "separation of interface implementation". Each different type is a compromise between the pros and cons.

  • interface chooses minimum reuse and maximum separation

  • It is easy to reuse general classes, but the interfaces are not separated

  • Abstract classes are somewhere in between.

As @MaxValue said, if the interface can have a constructor, it is almost the same as abstract class positioning.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template