0

I have a class that implements Comparator but not that I need my class to be Serializable How can I implement both of them ?

public class A implements Comparator<A>
{
}
4
  • Please rephrase. Your question makes no sense. Commented Mar 16, 2014 at 19:48
  • 1
    you want to implement Comparator and Serializable? Commented Mar 16, 2014 at 19:49
  • Oh never mind I got it Commented Mar 16, 2014 at 19:51
  • To expand on all of the answers, in Java you can only extend a single class, but you can implement unlimited interfaces. Commented Mar 16, 2014 at 19:51

4 Answers 4

2

It's a common misconception that Java does not have multiple inheritance. It doesn't have multiple inheritance of state, but it does have multiple inheritance of (declarations of) behavior, which is shown through interfaces. So you can have a single class implement multiple interfaces:

public class A implements Comparator<A>, Serializable {
}
Sign up to request clarification or add additional context in comments.

5 Comments

Not quite right. It has multiple inheritance of declarations of behavior. Interfaces lack implementation, so it's not truly multiple inheritance of behavior. Essentially, it's a bridge between true multiple-inheritance and duck-typing.
Technically, it still (as of 7) doesn't have inheritance of behavior, but at least that's kinda changing.
I guess you two are technically correct, at least for a few more days until Java 8 comes out. I'll try to reword the answer.
@aruisdante I updated the answer in accordance with your comment. Downvoter: please see the revised answer.
@arshajii could you add more explanition about state and behavior, I don't understand how two are different ?
1
import java.io.Serializable;
import java.util.Comparator;

public class A implements Comparator<A>, Serializable {

    @Override
    public int compare(A arg0, A arg1) {
        return 0;
    }
}

Comments

0

You can implement more than one interface, simply separate them with commas:

class A implements Comparator<A>, Serializable {
}

Comments

0

You can extend only one superclass but you can implement as many interfaces as you like, e.g.

public class A extends B implements Comparator<A>, Serializable {
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.