Download Understanding Inheritance and Class Hierarchies in Object-Oriented Programming and more Study notes Object Oriented Programming in PDF only on Docsity! Class Hierarchies & Sub Classes Inheritance Using inheritance, a derived class can be defined as an extension of a base class. The inheriting (derived) class inherits all the behavior and state memory of the base class. In addition, it is free to add its own member data and functions - so-called extensions or specializations. Code for Single Inheritance Class A { Int a; public: int b; void get_ab ( ) { a=5; b=10;} int get_a ( ) { return a;} void show_a ( ) { cout<<a;} } Class B : public A { int c; public: void mul ( ) { c=b * get_a ( );} void display ( ) { cout <<“a=“<<get_a( )<<“\n”; cout <<“b=“<<b<<“\n”; cout <<“c=“<<c<<“\n”; } } Int main ( ) { B b; b.get_ab ( ); b.mul ( ); b.display ( ); } Output: a=5, b=10, c=50. Multiple Inheritance Class N Parent class2 Base Class2 Class M Parent class1 Base class1 Class P Child class Derived Class Code for multiple inheritance class M { Protected: int m; public: void get_m (int x) { m=x; } } class N { Protected: int n; public: void get_n (int x) { n=x; } } Class P : public M, public N { public: void display ( ) { cout <<“m=“<<m( )<<“\n”; cout <<“n=“<<n<<“\n”; cout <<“m*n=“<<m*n<<“\n”; } } int main ( ) { P p; p.get_m (10 ); p.get_n (20 ); p.display ( ); } Output: m=10, n=20, m*n=200. Hybrid Inheritance Class A Parent class for B & C Class B Child class for A Parent class for C Class C Child class for A & B Class D Parent class for C Example for Hybrid Inheritance Student Class Roll No GetNum ( ) PutNum ( ) Test Class Sub1, Sub2 GetMarks ( ) PutMarks ( ) Result Class Total=sub1+sub2+ score Display ( ) Sports Class Score GetScore ( ) PutScore ( ) Class Hierarchies Employee Class Name, Number Manager Area Reporting_To Scientist No_Publications Research_Area Labour Role Experience Reporting_To All java classes are subclasses In fact, in Java, all classes must be derived from some class. Which leads to the question "Where does it all begin?" The top-most class, the class from which all other classes are derived, is the Object class defined in java.lang. Object is the root of a hierarchy of classes. Example code public class Animal { } public class Mammal extends Animal { } public class Reptile extends Animal { } public class Dog extends Mammal { } public class Dog extends Mammal{ public static void main(String args[]){ Animal a = new Animal(); Mammal m = new Mammal(); Dog d = new Dog(); System.out.println(m instanceof Animal); System.out.println(d instanceof Mammal); System.out.println(d instanceof Animal); } } Animal (Super Class) Mammal (Subclass for animal) (Super class for Dog) Reptile (Sub class) Dog (Subclass)