Questions about using interface anonymous classes and overriding.

Asked 2 years ago, Updated 2 years ago, 27 views

I understand that the interface cannot be instantiated, but I have seen frequent use of the Comparator as an anonymous class. In this case, is it used without being instantiated?

As far as I know, the method in the interface should be overridden after inheriting it as a public abstract

Why doesn't the compilation error occur to override the other abstract methods besides intcompare (To1, To2) in the comparator?

Thank you.

java

2022-09-22 16:50

1 Answers

I understand that the interface cannot be instantiated, but I have seen frequent use of the Comparator as an anonymous class. In this case, is it used without being instantiated?

Anonymous class is literally an unnamed class. This can be instantiated.

Typically, you create a class that has appealed the interface and create instances of this class. However, it is often used like Comparator, and doing this every time increases the amount of code, reduces readability, and is very cumbersome.

For this reason, an anonymous class was introduced to create an implementation for the interface and to create an instrument.

However, this was also inconvenient, so Lambda was introduced from Java 8, making it easier to use.

I know that the method in the interface needs to be overridden after inheriting it as a public abstract, but why doesn't a compilation error occur to override other abstract methods other than comparator intcompare(To1, To2);.

The question is a little hard to understand.

public abstract is used to create abstract classes or abstract methods, not to override methods in an interface. Therefore, you can create a method without writing abstract.

Comparator has no abstract method except intcompare(To1, To2) in Comparator. Therefore, overriding other methods in the Comparator other than intcompare(To1, To2) is not mandatory and compilation errors do not occur.


2022-09-22 16:50

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.