CSC/ECE 517 Fall 2011/ch17 5b uo: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
Line 115: Line 115:
   
   
}
}
</pre>
 
</div>
<div>
<span style="color:red">
<span style="color:red">
<p>//output</p>
<p>//output</p>
Line 123: Line 121:
<p>//duckling sounds quack!</p>
<p>//duckling sounds quack!</p>
</span>
</span>
</pre>
</div>
</div>



Revision as of 01:37, 1 November 2011

When to use Inheritance

Introduction

Inheritance is a useful programming concept, but it is easy to abuse this concept. Often interfaces or delegation are better options. In this wiki chapter, we will discuss the situations when to use and when not to use inheritance. Inheritance is a good choice when

  • Your inheritance hierarchy represents an "is-a" relationship and not a "has-a" relationship.
  • You can reuse code from the base classes.
  • You want to implement polymorphism.
  • The class hierarchy is reasonably shallow, and other developers are not likely to add many more levels.
  • You want to make global changes to derived classes by changing a base class.

These points are discussed in detail below

Representing "Is-a" Relationship

A "Is-a" relationship can be represented by inheritance in most cases.For example cat "Is-a" animal. Lets consider a scenario of an organization where a person can either be a manager or an employee. Thus a employee "Is-a" person. Can this "Is-a" relationship be represented by inheritance? Let us assume that an employee can be represented as a subclass of person. What happens when the employee is promoted to become a manager? In this case when a employee is promoted to become a manager, all the references of the employee has to be removed which can be cumbersome. Hence the employee "Is-a" person relation cannot be represented by inheritance. So how do we represent this relationship? This problem can be solved by using referencing in the following way:

public class Person
{
   private String name;
   private String gender;
   private String address;
   public String getAddress()
   {
       return address;
   }
   
   ...other methods and data...
}
public class employee
{
   private Person me;
   public String getAddress() { return me.getAddress(); }
   public float getSalary() {}
   ...other methods and data...
}

Hence a class x shouldn't be a super class of class y based on a role played by y that is modeled by x.

A "Is-a" relationship between a superclass S and a subclass T can be represented by inheritance only if S and all its references can be replaced by T without losing correctness of the program. This is called Liskov's Substitution Principle (LSP) [1]. An example where LSP determines the fate of a "Is-a" relationship is the well-known square is a rectangle scenario. Even though a square is a rectange it cannot be a subclass of rectange because all the references to a rectange cannot be replaced by a square. Let us assume we replace a rectangle object of length 10 and height 5 by a square object of length 10. The area of the square will be 100 and cannot replace the rectangle whose area is 50.

Code Reuse

The idea of reusability is one of the key components of Object-oriented (OO) design. OO Programming encapsulates attributes and methods that manipulates the data into one small unit, a unit that can be instantiated multiple times, hence supporting reusabilty of code. Inheritance further enables reusabilty of code and removal of redundant code. In inheritance the subclass inherits all the attributes and methods of the superclass, hence, removing the need of defining common attributes and methods in two different classes. But representing the relationship between objects having some common attributes and/or methods by inheritance might not be appropriate all the time. The rule of thumb would be to evaluate if the relationship satisfies the same two principles required by a "Is-a" relationship to be represented as inheritance.

  • A class x shouldn't be a super class of class y based on a role played by y that is modeled by x.
  • A relationship between a superclass S and a subclass T can be represented by inheritance only if S and all its references can be replaced by T without losing correctness of the program. This is called Liskov's Substitution Principle (LSP)

Inheritance-based Polymorphism

Polymorphism meaning many forms has the same meaning in Object Oriented programming language as it is the ability to have an attribute, method or an object in more than one form. Operator overloading is a good example of polymorphism. In java a "+" operator adds two integer type operands while it concatenates two string type operands. Hence the "+" operator can exist in multiple forms. Inheritance provides an opportunity for polymorphism by leveraging method overloading or method overriding. Method overriding is a means by which a subclass can override methods inherited from superclass. The next question that follows is when and how method overriding can be useful. lets assume a duck class and a hen class. Duck "Is-a" bird. Hen also "Is-a" bird. They have a lot in common but they produce different sounds. So, having bird as a superclass with a talk method that is overridden by the subclasses hen and duck would make a good program.

public class bird {
        public String name;
 
        public bird(String name) {
                this.name = name;
        }
 
        public String sounds() {
                return "Unknown bird!!";
        }
}
public class duck extends bird {
 
        public duck(String name) {
                super(name);
        }
 
        @Override
        public String sounds() {
                return "quack!" ;
        }
}
  
public class hen extends bird {
 
        public hen(String name) {
                super(name);
        }
 
        @Override
        public String sounds() {
                return "cocock!";
        }
}
public class overridingLeveragedByPolymorphism {
 
        public static void main(String[] args) {
                ArrayList<bird> birds = new ArrayList<bird>();
                birds.add(new hen("chicken"));
                birds.add(new duck("duckling"));
 
                for (int i=0;i<birds.size();i++) {
                        thisBird = birds.get(i); 
                        System.out.println(thisBird.name + " sounds " + thisBird.sounds());
                }
        }
 
}

<span style="color:red">
<p>//output</p>
<p>//chicken sounds cocock!</p>
<p>//duckling sounds quack!</p>
</span>

Shallow Class Hierarchies

Global Changes to Derived Classes Through the Base Class

Composition vs Inheritance

Drawbacks of inheritance

Inheritance is not without its own set of drawbacks. If inheritance is applied without due consideration problems can arise. In some situations it can:

  • Reduce the comprehensibility of code.
  • Make maintenance harder.
  • Make further development harder.
  • Reduce reliability of code.
  • Reduce overall reuse.

Conclusion

<EDIT THIS> We have considered the benefits and drawbacks of inheritance within an object oriented programming language. We have challenged the general perception that inheritance is by its very nature always good and have considered when it should and should not be used. We have re-assessed compositional reuse and made the case that it is as important, in an object oriented language, as inheritance in order to achieve the maximum possible reuse. We can therefore provide a summary of our findings that can be used as a set of guiding principles for object oriented development: · Avoid code dependency except on published protocol. · For structural inheritance direct extension is fine.

References