sabaTEL.net

Java, MySQL, Avaya

Differences between abstract Class and Interface

Both try to achieve abstraction in Java but there are some fundamental differences between them:

  • An interface it’s an empty shell, there are only signatures of the methods, they are not implemented. The interface is just a pattern, a ‘contract’ established about what it can do without saying how to do it.
  • Abstract classes can have members, abstract methods (not implemented) and methods, using any visibility. Interfaces can have members and method declarations and all of them must be public.
  • A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same public visibility.
  • If we add a new method to an interface, that breaks the established contracts with all classes that implement it, so the method implementation will need to be added to all those classes. Adding a new method to an abstract class it’s not such a big deal, because we can always define default behaviour.

Maybe, I have confused you now, so probably best to look at very simple examples:

As you can see from the above, for an abstract class we can have abstract and non abstract methods living together, the only requirement is that the class has the abstract attribute in front of it.

With interfaces we know that the implementation of any of the methods is not allowed. So you should never see a ‘{ }’.

Advertisements

June 30, 2013 Posted by | Java | 1 Comment

What it means if you don’t override equals()

If you don’t override a class’s equals() method, you won’t be able to use those objects as a key in a hashtable and you probably won’t get accurate Sets, such that there are no conceptual duplicates.

The equals() method in class Object uses only the == operator for comparisons, so unless you override equals(), two objects are considered equal only if the two references refer to the same object.

Note the there are 2 things to be done in order to make a valid equality comparison.

  • Be sure that the object being tested is the correct type. It comes in polymorphically as type Object, so you need to do an instanceof test on it. Having two objects of different class types be considered equal is usually not a good idea.
  • Compare the attributes we care about (in this case, just moofValue)

Only the developer can decide what makes two instances equal. (For best performance, you’re going to want to check the fewer number of attributes.)

equals(), hashCode() and toString() methods are all public. The following would not be a valid override of the equals() method:

Remember to check the argument types as well, the following method is an overload, but not an override of the equals() method:

June 30, 2013 Posted by | Java | Leave a comment