Java Class, Sub-Class, Abstract Class, Interface

How do you know when to create a class, sub-class, abstract class, or interface?

  • Create a class when your object no longer passes the IS-A test.
  • Create a subclass when you would like to add more granularity and or functionality to a more specific type of the class it will extend.
  • Create an abstract class (which can contain both abstract, and non-abstract methods) when you would like to create a template for groups of sub-classes, it’s like updating their “contract”.
  • Create an interface when you would like multiple different types to be able to have the ability to play a certain role. Keep in mind that any class can implement an interface. This is great for polymorphism because it allows you to have different types from anywhere in multiple inheritance trees playing well together. Just use the interface as a generic return type, parameter, or reference, and anything that implements it will be able to have its methods run on it. This is important because the compiler will only let you run methods that reside in the reference type, it doesn’t matter what the object is. Think of how not-flexible it would be, if you couldn’t use interfaces? You would have to guarantee that every new object write their code to be identical to your design. The whole point of interfaces and super-classes is to establish a code “contract”, that mandates your code will always play well with others. Interfaces are 100% abstract, and all concrete classes that implement them must create a method body for every method.

Extend once (avoid the Double Diamond of Death), implement multiple times. If you want to override a super-class’s method (or methods), but still use their original functionality, use super.methodName() inside your overriddin method’s body.

Tags: ,

Leave a Reply