Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What methods and interfaces do you (almost) always implement in classes?

Tags:

java

Which methods and interfaces do you always implement in your classes?

Do you always override equals()? If you do, do you also do hashcode()? toString()? Do you make it a habit to implement the Comparable interface?

I've just written some code where I needed to implement compareTo() and override equals() to get my program to work in a sane manner; I now start seeing ways of using these everywhere...

What do y'all think?

like image 706
masher Avatar asked Apr 04 '09 23:04

masher


People also ask

Which method must be implemented when using an interface?

Yes, it is mandatory to implement all the methods in a class that implements an interface until and unless that class is declared as an abstract class. Implement every method defined by the interface.

What methods must be implemented when writing a class that implements both of these interfaces?

A class that implements an interface must implement all the methods declared in the interface. To implement interface use implements keyword.

How many interfaces should a class implement?

A class can implement more than one interface at a time. A class can extend only one class, but implement many interfaces. An interface can extend another interface, in a similar way as a class can extend another class.


2 Answers

I usually don't implement things in advance unless I need them.

If my class contains data members and I plan to store it somewhere, I will usually implement equals, hashCode, and comparable.

However, I found that most of my classes do not have this issue so there's no point to do it. For example, if your class revolves around functionality on other objects rather than data, why bother? If you have one instance or is organized hierarchically (e.g., a GUI widget or window), why bother?

Don't implement things you don't need, but always make sure to check whether they are needed or not because Java will generally not warn you.

Also, make sure to use your IDE or something like Apache commons to generate these functions. There is rarely a need to hand-code them.

As for toString, I rarely implement it until I find myself debugging and needing a better presentation in the Eclipse debugger (e.g., instead of object ID). I am afraid of implicit converts and never use toString when generating output.

like image 77
Uri Avatar answered Oct 27 '22 01:10

Uri


(Almost) Always toString().

It is usually helpful for debugging purposes.

like image 23
jjnguy Avatar answered Oct 26 '22 23:10

jjnguy