Aman
Aman

Reputation: 838

Interface implementation in java by comparator

I got confused while stuyding java in deep with the core concept.

what i have studied is, if you have interface

public interface interfaceconcept {

    public void heyyou(String s);
    public abstract void nono(String s);
    public void kolk(int i);


}

and you have a class which implements the interface then you have to write the body of all the methods

  public class implementation implements interfaceconcept{

    @Override
    public void heyyou(String s) {
        // TODO Auto-generated method stub

    }

    @Override
    public void nono(String s) {
        // TODO Auto-generated method stub

    }

    @Override
    public void kolk(int i) {
        // TODO Auto-generated method stub

    }

    }

if you dont want to write the methods you can use abstract class

Now i was studing about comparator, and while inpecting its class i found it is an interface

public interface Comparator<T> { 
//
}

now it implemented it in another class, firstly it gave me an error saying.

The type Order must implement the inherited abstract method Comparator.compare(Order, Order)

i have added all the method by clicking add unimplemented method and remove all but one.

but when i compiled it, it simply compiled why? am i not supppose to add all the unimplemented methods of comparator interface as per the rules of java?

Also one of its method in comparator class is

default Comparator<T> reversed() {
        return Collections.reverseOrder(this);
    }

what is the point if you have written the implementation of one method in interface itself? you cant write any body of the method, if i m correct.

public class Order implements Comparator<Order>{

    @Override
    public int compare(Order o1, Order o2) {
        // TODO Auto-generated method stub
        return 0;
    }


    }

Upvotes: 0

Views: 749

Answers (1)

Lew Bloch
Lew Bloch

Reputation: 3433

If you look at the Javadocs for Comparator<T> https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html you'll see that the only abstract method that is not default, not static, and not already implemented via inheritance from Object is compare(T, T). So it's the only method that is unimplemented in the interface, and therefore when you implement it you have implemented all the unimplemented methods in the interface.

Upvotes: 1

Related Questions