Interfaces and abstract classes provide a more structured way to separate interface from implementation
abstract Classes and Methods
Abstract method has only a declaration and no method body. If a class contains one or more abstract methods, the class itself must be qualified as abstract, otherwise the compiler gives an error message.
- You cannot create an object of an abstract class.
- If you inherit from an abstract class and you want to make object of the new type, you must provide method definitions for all the abstract methods in the base class.
- If you don't implement those abstract methods, the derived class should be declared as abstract.
- It's possible to make a class abstract without including any abstract methods.
The reason to use abstract classes and methods:
- They make the abstractness of a class explicit, and tell both the user and compiler how it was intended to be used.
- They are useful refactoring tools, since they allow you to easily move common methods u the inheritance hierarchy.
Interfaces
The interface keyword produces a completely abstract class (no implementation at all). It allows the creator to determine method names, argument lists, and return types, but no method bodies. However, an interface is more than just an abstract class taken to the extreme, since it allows you to perform a variation of "multiple inheritance" by creating a class that can be upcast to more than one base type.
- As with a class, you can add the public keyword before the interface keyword. If you leave off the public keyword, you get package access, so the interface is only usable within the same package.
- Methods in an interface are implicitly public. So when you implement an interface, the methods from the interface must be defined as public. Otherwise, they would default to package access, and you'd be reducing the accessibility of a method during inheritance., which is not allowed by the Java compiler.
- An interface can also contain fields, but these are implicitly static and final.