I read somewhere that the chain of inheritance breaks when you alter a behavior from derived class. What does "altering a behavior" mean here?
Using C# as an example, you could have a base class such as :
public class SomeBaseClass
public virtual void DoSomething()
And then a child class such as this:
public class MyChildClass : SomeBaseClass
public override void DoSomething()
Console.WriteLine("This method now does something completely different!");
However, if you added
base.DoSomething(); to the method
MyChildClass, it would call both the parent method (outputting "Hello world!") and the new method (outputting "This method..."). The order they are displayed depends on where you put the
base.DoSomething(); method call.
By avoiding calling the base method, I believe you would break the chain of inheritance, as it no longer performs the expected method of the parent class.
Another option is to use the
new syntax on the method like so:
new public void DoSomething()
This is called method hiding and lets you again define completely new behavior, but exposes a different method to the outside world, than the one that is visible by
SomeBaseClass. I haven't had a need to use this myself, but I understand it can be helpful in some situations.
Of course, your milage may vary for these syntaxes and commands depending on the language of choice, but the general idea is the same.
I read that Duplicating code is not a good practice, and its a maintenance nightmare. Again, does overriding an already implemented method in base class considered "Duplicating code"?
Duplicating code is a bad practice, as it can lead to errors during maintenance. Suppose you had a function that calculates a value using some complex arithmetic or the like. Instead of properly creating a method for it, you just copy and paste it a dozen times as needed. Now, when something changes (and it will! Oh, things will change) you have to locate it a dozen times, and put the correct code in a dozen times. By putting it in a method you just change it once, and everything that uses that code is corrected as well.
Abstraction and inheritance reduce code duplication, because you can make a base class or method as a template, and you only have to write it once. Smart object design allows you to make highly-reuseable code which is proven to be tested and error-free. Plus, following inheritance guidelines will allow for child classes that can use code under the assumption that it "just works", and it can override the implementation, providing new or more specific behavior for itself as needed.