Monday, February 20, 2017

Characteristics of inheritance


  1. A private data member or method cannot be inherited by sub class. However if there is a public method in parent class which further access its private members then such methods can be directly used from its child class.
  2. Only protected and public members can be inherited.
  3. A class cannot have more than one parent class, in short multiple inheritance is not allowed in java. (Available in C++). However we can achieve indirectly using "interface" concept which we will discuss in detail in next to next chapter.
  4. Parent class can always store reference of its child class but vice versa is not possible.
  5. e.g.
    Supplier supplier1 = newSupplier();             //Correct
    Supplier supplier2 = newXYZLimited ();          //Correct
    XYZLimited xyzSupplier1 = newXYZLimited();      //Correct
           XYZLimited xyzSupplier2 = newSupplier();        //Incorrect
  6. In sub class the inherited members can be used directly just like its local members.
  7. We can declare a field in sub class with same name as declared in super class, but this is not recommended.
  8. We can declare new fields in sub class which are not in super class (e.g. cubicalSize in above example).
  9. We can write a new instance method in sub class with same signature (return type, name, parameters) as the one in super class, this process is known as method overriding.
  10. A sub class constructor can call super class constructor using “super” keyword.
  11. A nested class inside parent class has access to all private members (field & methods), and if that nested class is either public or protected then the child class can access it directly, thus the private members are accessed indirectly through inner class of parent. We will discuss about nested class in later chapters.

No comments:

Post a Comment