Sunday, December 25, 2016

Java Coding- Inheritance Rules

Inheritance should be used wisely. Purpose of inheritance is to have a parent-child (Superclass-Subclass) relationship between objects. In result, it facilitates code reuse. But don't use Inheritance just for code reuse. 
Following two principles help you to use inheritance wisely-

is A? Principle

It helps you decide if you should inherit a class from other i.e. is the new class should or should not extends a super class. So before you decide to extend ask the below question-

Is a "Circle" a "Shape"?
Is a "Triangle" a "Circle"?
Is a "Cat" an "Animal"?

If answer is "Yes" then you should extend the super class.
If answer is "No" then you should NOT extend the super class.

has A? Principle

It helps you decide if a class should have a field or is it relevant to add a new field to a class? Ask below question-

Has a "Circle" has a "radius"?
Has a "Triangle" has a "radius"?

If answer is yes then you should have the field in the class otherwise NOT.


Inheritance facilitates one more Advantage that is in form of another principle-

Liskov Substitution Principle

Any child type of a parent type should be able to stand in for that parent without things blowing up. Reverse of this is not true i.e. you can not replace a child type object with it's parent type object. If you try do so i.e. by means of type casting the parent type object, there is a risk that it may blow up things.

Consider an example where "Animal" <---- "Dog" i.e. Dog extends Animal

A. Suppose a  method which accepts Animal - makeNoise(Animal a). You can always call this method with child type object i.e. makeNoise(d) where d is an object of class Dog.

B. Take another method which accepts Dog - sniffDanger(Dog d). Now you can NOT call this method with parent type object i.e. sniffDanger(a) where a is an object of class Animal. Even if you try to typecast a, something like this: sniffDanger((Dog) a), there is high possibility that it may blow up things, so not a safe approach.

No comments:

Post a Comment

CDN | Clearing Cloudflare cache

In order to clear Cloudflare cache automatically via code, follow below steps: 1. Develop Custom TransportHandler Develop a custom Trans...