Inheritance In C++ Vs Java

Inheritance is a feature in object-oriented programming which is very similar to the way we inherit characteristics from our parents. Characteristics in object-oriented programming terms are attributes and behaviors of a class—that is, the data and methods of a class.

Inheritance is a cornerstone of object-oriented programming because it enables objects to inherit attributes and behaviors from other objects, thereby reducing the amount of new code that must be designed, written, and tested each time a new program is developed.A hierarchical relationship develops as classes inherit from other classes within a program.

Inheritance provides a way to distribute control for development and maintenance of objects. For example, a programmer might be responsible for creating and maintaining the student object. Another programmer might develop and maintain the graduate student object. Whenever a change occurs that affects all students, those changes are made to the student object and are then inherited by the graduate student object. Only the programmer responsible for the student object needs to address those changes because the graduate student object inherits any changes made to the student object.

Inheritance also provides a way to limit access to attributes and behaviors. As we know public, private, and protected access specifiers are used to determine parts of the program that can access attributes and behaviors.

Public access specifier is used to define members of a class that are available to other members of the class, other classes, and to all parts of the program.

Private access specifier is used to define members that are only accessible by members of the same class only. They are unavailable to other classes and other parts of the program.

The protected access specifier identifies attributes and behaviors that are available to members of the class and to other classes that are inherited from it.

The purpose of limiting access to attributes and behaviors is to ensure the integrity of the object by controlling how other classes and parts of the program interact with it.


The Class Hierarchy



The hierarchical relationship between classes is sometimes referred to as a parent-child relationship. In a parent-child relationship, the child inherits all attributes and behaviors of the parent, and it uses the parent’s access specifier to control how those inherited items are available to other classes or functions.

In C++ the parent is referred to as a base class, and the child is called a derived class. In Java, the parent is the super class, and the child is the subclass.

Programmers use the “is a” test to determine if a relationship exists between classes. The “is a” test determines if the child “is a” parent. For example, a graduate student “is a” student. If an “is a” relationship makes sense, then a parent-child relationship exists and the child can inherit from the parent. If an “is a” relationship doesn’t make sense, then a parent-child relationship doesn’t exist and the child cannot inherit from the parent, as in the case of an automobile and airplane. An automobile “is a(n)” airplane? This is nonsense, so we shouldn’t attempt to create such a relationship.

Types of Inheritance



We have three ways to implement inheritance in a program:
  • Simple inheritance,
  • Multiple inheritance, and
  • Level inheritance
Each enables a class to access attributes and behaviors of another class using slightly different techniques.

Simple inheritance

Simple inheritance occurs when there is one parent-child relationship. That is, one child inherits from one parent.

The following diagram depicts this inheritance:



Two classes are represented in this diagram. These are the Student class and the GradStudent class. The Student class is the parent in this relationship and is inherited by the GradStudent class, which is the child.

Inheritance occurs from the parent to the child. A parent class cannot access attributes and behavior of a child class. The Student class cannot call the Write() and Display() members of the GradStudent class. However, the GradStudent class can call the Student class’s versions of these members.

Multiple inheritance

Multiple inheritance occurs when the relationship involves multiple parents and a child. In other words, the child inherits from more than one parent.

The following diagram depicts this inheritance:



In this example, the GradStudent class inherits from both the Person class and the Student class. The Person class and the Student class are both parents to the GradStudent class, which is the child in this relationship.The GradStudent class inherits the characteristics of a person from the Person class. These are the weight, height, and sex attributes and the Walk() and Sit() methods.

We must keep certain factors in mind when implementing multiple inheritance:
  • Each class that is inherited must pass the “is a” test.
  • Parent classes are independent of each other.
  • Inheritance occurs in one direction from the parent to the child, which is identical to simple inheritance.
  • Any number of parent classes can be inherited by a child class as long as they pass the “is a” test.
  • Multiple inheritance can lead to an interesting and potentially confusing issue referred to as the diamond problem. Imagine that we have a base class called IDObject, which contains an ID attribute to hold a unique ID value. Now, we derive from that class a Student and Instructor class. So far we have a Student and Instructor class, both of which have inherited a unique ID attribute. Now, imagine we create a TeacherAssistant class derived from both Student and Instructor. This new class has two unique IDs. This is called the diamond problem because if we draw the inheritance chart, it will be shaped like a diamond. Though we can make it work, this example can lead to confusion when we want to get the ID for the TeacherAssistant class:
    Which one do we want?
    Whereas C++ supports multiple inheritance, Java does not. Java provides something called interfaces to implement the concept of multiple inheritance.
Level Inheritance

Level inheritance happens when a child inherits from a parent and then becomes a parent itself to a child.

The following diagram depicts this inheritance:



The Person class is a parent class that is inherited by the Student class. The Student class is a child class in the Person class–Student class relationship. However, another parent-child relationship exists when the GradStudent class inherits the Student class. In this relationship, the Student class is the parent class, and the GradStudent class is the child class. This means that the Student class has a duel role in inheritance. It is both a child and a parent.

Each parent-child relationship is considered a level. That is, the Person class–Student class relationship is the first level, and the Student class– GradStudent class is the second level. We can have as many levels as required by our program. However, many programmers stop at three levels because it becomes a bit unwieldy to manage beyond three levels.

In level inheritance, the final child class, which is the GradStudent class in the above example, inherits attributes and behaviors for all classes in the level chain. Here’s how this works: The Student class inherits attributes and behaviors from the Person class. Once inherited, these attributes and behaviors are considered members of the Student class, just as if they were defined in the Student class. When the GradStudent class inherits from the Student class, the GradStudent class has access to the Student class’s attributes and behavior that now include those inherited from the Person class. Only attributes and behaviors designated as public or protected are inherited.

Although the last child class (that is, the GradStudent class) doesn’t directly inherit from the Person class, the Person class still must pass the “is a” test. That is, a graduate student “is a” person.

There is an important difference between multiple inheritance and level inheritance. In multiple inheritance, parent classes are independent of each other. In level inheritance, a parent class that is also a child class (that is, the Student class) can access other parent classes within the leveling chain.

Now we will look at the different types of inheritance in C++ and Java.

Simple Inheritance Using C++



Simple inheritance is implemented using C++ by defining two classes. One class is the base class, and the other class is the derived class. We musr make sure that the derived class passes the “is a” test. That is, the derived class “is a” base class.

The following example illustrates how to use simple inheritance in C++. The two classes defined in this program are the Student class and the GradStudent class. The Student class is the base class, and the GradStudent class is the derived class.

The Student class definition contains two member functions: Write() and Display(). Both of these are defined within the public access specifier section of the class definition.

Code:
#include <iostream>
#include <string.h>
using namespace std;
class Student
{
   protected:
      int m_Graduation, m_ID;
      char m_First[16], m_Last[16];
   public:
      virtual void Display()
         {
            cout << "ID: " << m_ID << endl;
            cout << "First: " << m_First << endl;
            cout << "Last: " << m_Last << endl;
            cout << "Graduation: " << m_Graduation << endl;
         }
      void Write( int ID, char First[], char Last[], int Graduation )
      {
         m_ID = ID;
         strcpy( m_First, First );
         strcpy( m_Last, Last );
         m_Graduation = Graduation;
      }
      Student()
      {
         m_ID = m_Graduation = 0;
         m_First[0] = m_Last[0] = '\0';
      }
};
The Write() member function receives student information as arguments that are then assigned to attributes of the Student class. The Display() member function displays the values of those attributes on the screen.The attributes of the Student class are defined in the protected access specifier section of the class definition. These attributes are the student ID, student name, and whether or not the student graduated.

The GradStudent class definition follows the Student class definition in this example. In C++ we specify that a derived class inherits a base class by using the colon, the access specifier (optional), and the name of the base class in the class header. In this example, the GradStudent class is shown inheriting the Student class:

Code:
class GradStudent : public Student
{
   protected:
      int m_UndergradGraduation;
      char m_UndergradSchool[64];
      char m_Major[64];
   public:
      GradStudent()
      {
         m_UndergradGraduation=0;
         m_UndergradSchool[0] = m_Major[0] = '\0';
      }
      virtual void Write( int ID, char First[], char Last[], int Graduation,char  Major[], char  UndergradSchool[], int UndergradGraduation)
      {
         Student::Write( ID, First, Last, Graduation );
         strcpy( m_Major, Major );
         strcpy( m_UndergradSchool, UndergradSchool );
         m_UndergradGraduation = UndergradGraduation;
      }
      virtual void Display()
      {
         Student::Display();
         cout << "Major: " << m_Major << endl;
         cout << "Undergrad school: " << m_UndergradSchool << endl;
         cout << "Undergrad graduation: " << m_UndergradGraduation << endl;
      }
};
The GradStudent class contains the Write() and Display() member functions in its public access specifier section. Notice that the Write() member function receives both student information and graduate student information as argument. The student information is assigned to attributes of the Student class (using the Student class’s Write() method), and graduate student information is assigned to attributes of the GradStudent class. Likewise, the Display() member function of the GradStudent class displays the values assigned to attributes of both classes.

The Write() and Display() member functions of the GradStudent class have access to attributes of the Student class because the Student class is inherited by the GradStudent class and because attributes of the Student class are contained within the protected access specifier of that class.

The GradStudent class defines three attributes that specify the year the student received an undergraduate degree, the name of the undergraduate school, and the student’s major. All these attributes are defined within the private accessor specifier of the class, making them accessible only to member functions of the GradStudent class.
Code:
int main()
{
   Student s;
   GradStudent g;
   s.Write( 100, "Hari", "Kimi", 2008 );
   g.Write( 101, "Elizabeth", "Jonny", 2008, "Comp Sci", "Canada", 2002 );
   s.Display();
   g.Display();
   return 0;
}
An instance of the GradStudent object called g and a Student object called s are declared within the main() function of the program. The instance name is then used to call the Write() member function of the GradStudent class and is passed student information. This information is then shown on the screen when the Display() member function is called.

Here’s what is displayed on the screen when the entire program is executed:

ID: 100
First: Hari
Last: Kimi
Graduation: 2008
ID: 101
First: Elizabeth
Last: Jonny
Graduation: 2008
Major: Comp Sci
Undergrad school: Canada
Undergrad graduation: 2002

Simple Inheritance Using Java



Simple inheritance is implemented in a Java application using a technique similar to that used in the C++ example. The Java application must define a super class and a subclass, as shown in the following example. The Student class is the super class, which is the same as a base class in C++. The GradStudent class is the subclass, similar to the derived class in the previous example.

The Student class definition is the same as the Student class definition in C++, except that the access specifiers are placed in each statement and method definition. The GradStudent class definition is very similar to the GradStudent class definition in C++, except for two variations.

First, the extends keyword is used in Java to signify inheritance. The extends keyword must be followed by the name of the super class that is being inherited, which is the Student class in this example.

The other variation is found within the Display() method. The first statement within the Display() method definition calls the Student class’s Display() method using the keyword super. You use super whenever you want to reference a member of the super class. In this example, the Student class’s Display() method causes values of the Student class attributes to be displayed on the screen. The second statement within the GradStudent class’s Display() method definition causes attributes of the GradStudent class to be shown on the screen following the student information.

Code:
class Student 
{
 protected int nID, nGraduation;
 protected String sFirst, sLast;
 public Student() 
 {
  nID = 0;
  nGraduation = 0;
  sFirst = new String();
  sLast = new String();
 }

 public void Display() 
 {
  System.out.println("ID: " + nID);
  System.out.println("First: " + sFirst);
  System.out.println("Last: " + sLast);
  System.out.println("Graduation: " + nGraduation);
 }

 public void Write( int ID, String First, String Last, int Graduation ) 
 {
  nID = ID;
  sFirst = First;
  sLast = Last;
  nGraduation = Graduation;
 }
}

class GradStudent extends Student 
{
 String sMajor, sUndergradSchool;
 int nUndergradGraduation;
 public GradStudent() 
 {
  sMajor = "";
  sUndergradSchool="";
  nUndergradGraduation=0;
 }
 public void Display() 
 {
  super.Display();
  System.out.println("Major: " + sMajor );
  System.out.println("Undergrad Graduation year: " +
  nUndergradGraduation);
  System.out.println("Undergrad School: " + sUndergradSchool );
 }
 public void Write( int ID, String First, String Last, int Graduation, String Major, String UndergradSchool, int UndergradGraduation ) 
 {
  super.Write( ID, First, Last, Graduation);
  sUndergradSchool = UndergradSchool;
  sMajor = Major;
  nUndergradGraduation = UndergradGraduation;
 }
}
public class StudentApp 
{
 public static void main(String[] args) 
 {
  Student s = new Student();
  GradStudent g = new GradStudent();
  s.Write( 100, "Micky", "Liza", 2008);
  g.Write(101, "Mary", "Emy", 2008, "Computer Science", "Canada", 2002);
  s.Display();
  g.Display();
 }
 public static void Display( Student s ) 
 {
  s.Display();
 }
 public static void Display( GradStudent g ) 
 {
  g.Display();
 }
}
The main method of this example is identical to the main() function of the C++ version of this application, except this example uses Java syntax to declare an instance of the GradStudent class.

Here’s what the following program displays on the screen:

ID: 100
First: Micky
Last: Liza
Graduation: 2008
ID: 101
First: Mary
Last: Emy
Graduation: 2008
Major: Computer Science
Undergrad Graduation year: 2002
Undergrad School: Canada

Level Inheritance Using C++



Level inheritance is implemented in C++ by defining at least three classes. The first two classes have a parent-child relationship, and the second and third classes must also have a parent-child relationship. Each child class must pass the “is a” test in order to inherit from the parent class.
The following example shows level inheritance in a C++ program. Three classes are defined in this example: the Person class, the Student class, and the GradStudent class. The Person class is a base class and is the parent in the parent-child relationship with the Student class. The Student class is the derived class in this relationship. That is, the Student class inherits from the Person class.
The Person class defines two member functions within the public access specific section of the class definition. These are Write() and Display(). The Write() member function assigns information about a person that is received as arguments to the attributes of the class. The Display() member function shows values of those attributes on the screen.
Both the Student class definition and the GradStudent class definition are the same as shown above.
However,the Student class inherits from the Person class and that the GradStudent class inherits from the Student class.
The Student class is both a derived class and a base class. It is a derived class in the parent-child relationship with the Person class, and it is a base class in the parent-child relationship with the GradStudent class.

Code:
#include <iostream>
#include <string.h>
using namespace std;
class Person
{
   protected:
      int m_ID;
      char m_First[16], m_Last[16];
   public:
      Person()
      {
         m_ID = 0;
         m_First[0] = m_Last[0] = '\0';
      }
      virtual void Display()


      {
         cout << "ID: " << m_ID << endl;
         cout << "First: " << m_First << endl;
         cout << "Last: " << m_Last << endl;
      }
      void Write( int ID, char First[], char Last[] )
      {
         m_ID = ID;
         strcpy( m_First, First );
         strcpy( m_Last, Last );
      }
};
class Student : public Person
{
   protected:
      int m_Graduation;
   public:
      virtual void Display()
      {
         Person::Display();
         cout << "Graduation: " << m_Graduation << endl;
      }
      void Write( int ID, char First[], char Last[], int Graduation )
      {
         Person::Write( ID, First, Last );
         m_Graduation = Graduation;
      }
      Student()
      {


         m_Graduation = 0;
      }
};
class GradStudent : public Student
{
   protected:
      int m_UndergradGraduation;
      char m_UndergradSchool[64];
      char m_Major[64];
   public:
      GradStudent()
      {
          m_UndergradGraduation=0;
          m_UndergradSchool[0] = m_Major[0] = '\0';
      }
      virtual void Write( int ID, char First[], char Last[], int Graduation,
         char  Major[], char  UndergradSchool[], int UndergradGraduation )
      {
         Student::Write( ID, First, Last, Graduation );
         strcpy( m_Major, Major );
         strcpy( m_UndergradSchool, UndergradSchool );
         m_UndergradGraduation = UndergradGraduation;
      }
      virtual void Display()
      {
          Student::Display();
          cout << "Major: " << m_Major << endl;
          cout << "Undergrad school: " << m_UndergradSchool << endl;
          cout << "Undergrad graduation: " << m_UndergradGraduation << endl;
       }
};
int main()
{
   Student s;
   GradStudent g;
   s.Write( 100, "Hari", "Kimi", 2008 );
   g.Write( 101, "Elizabeth", "Jonny", 2008, "Comp Sci", "Canada", 2002 );
   s.Display();
   g.Display();
   return 0;
}
The Student class inherits members of the Person class that are defined in the public and protected access specifier sections of the Person class. This inheritance is passed along to the GradStudent class when the GradStudent class inherits from the Student class. Any member of the Person class that is accessible to the Student class is also accessible to the GradStudent class.
The main() function of this example is nearly identical to the main() function of the simple inheritance example, except the Write() member function is passed information about the person as well as about the student and the graduate student.

Here is the output of the program:

ID: 100
First: Hari
Last: Kimi
Graduation: 2008
ID: 101
First: Elizabeth
Last: Jonny
Graduation: 2008
Major: Comp Sci
Undergrad school: Canada
Undergrad graduation: 2002

Level Inheritance Using Java



Java implements level inheritance very similarly to how level inheritance is implemented in C++, as shown in this next example. The same three classes defined in the C++ program are also defined in this Java application. Each class has the same attributes and member methods that perform the same functionality as their counterparts in the C++ program.
The Person class is inherited by the Student class using the keyword extends. The Student class is inherited by the GradStudent class also using the keyword extends. The Display() method of the Student class and of the GradStudent class each call the Display() method of its super class in order to display values of the super class’s attributes. This is similar to how attributes of a super class are displayed in simple inheritance using Java.

Code:
class Person 
{
 protected int nID;
 protected String sFirst, sLast;
 public Person() 
 {
  nID = 0;
  sFirst = "";
  sLast = "";
 }
 public void Display() 
 {
  System.out.println("ID: " + nID);
  System.out.println("First: " + sFirst);
  System.out.println("Last: " + sLast);
 }
 public void Write( int ID, String First, String Last ) 
 {
  nID = ID;
  sFirst = First;
  sLast = Last;
 }
}
class Student extends Person
{
 protected int nGraduation;
 public Student() 
 {
  nGraduation = 0;
 }
 public void Display()  
 {
  super.Display();
  System.out.println("Graduation: " + nGraduation);
 }
 public void Write( int ID, String First, String Last, int Graduation ) 
 {
  super.Write(ID, First, Last);
  nGraduation = Graduation;
 }
}
class GradStudent extends Student 
{
 String sMajor, sUndergradSchool;
 int nUndergradGraduation;
 public GradStudent() 
 {
  sMajor = "";
  sUndergradSchool="";
  nUndergradGraduation=0;
 }
 public void Display() 
 {
  super.Display();
  System.out.println("Major: " + sMajor );
  System.out.println("Undergrad Graduation year: " +
  nUndergradGraduation);
  System.out.println("Undergrad School: " + sUndergradSchool );
 }
 public void Write( int ID, String First, String Last, int Graduation,String Major, String UndergradSchool, int UndergradGraduation ) 
 {
  super.Write( ID, First, Last, Graduation);
  sUndergradSchool = UndergradSchool;
  sMajor = Major;
  nUndergradGraduation = UndergradGraduation;
 }
}
public class StudentApp 
{
 public static void main(String[] args) 
 {
  Student s = new Student();
  GradStudent g = new GradStudent();
  s.Write( 100, "Micky", "Liza", 2008);
  g.Write(101, "Mary", "Emy", 2008, "Computer Science", "Canada", 2002);
  s.Display();
  g.Display();
 }
 public static void Display( Student s ) 
 {
  s.Display();
 }
 public static void Display( GradStudent g ) 
 {
  g.Display();
 }
}
The main() method in this example contains practically the same statements found in the simple inheritance example, except the Write() method is passed information about a person as well as information about a student and a graduate student. The Display() method within the main() method displays values of attributes of all the classes on the screen.

Here is what is displayed on the screen when you run the following program:

ID: 100
First: Mary
Last: Liza
Graduation: 2008
ID: 101
First: Mary
Last: Emy
Graduation: 2008
Major: Computer Science
Undergrad Graduation year: 2002
Undergrad School: Canada

Multiple Inheritance Using C++



This example introduces two new classes: Instructor and Worker. The Worker class contains attributes and methods for working with an income attribute. The Instructor class is derived from the Person class (inheriting the ID and the first and last name attributes and methods) as well as the Worker class. This is done to emphasize that a worker need not be a person to generate an income (for example, the worker could be a vending machine). However, an instructor is both a person and an income producer, so we use multiple inheritance.

The Instructor class has a parent-child relationship with both the Person class and the Worker class. The Person class and the Worker class are both base classes, and the Instructor class is the derived class.

Multiple inheritance is specified in the class header of the derived class, as shown in the Instructor class definition of this example. The class names of classes inherited by the derived class are specified to the right of the colon after the accessor specifier. Each class inherited by the Instructor class must be separated by a comma.

Code:
#include <iostream>
#include <string.h>
using namespace std;
class Person
{
   protected:
      int m_ID;
      char m_First[16], m_Last[16];
   public:
      Person()
      {
         m_ID = 0;
         m_First[0] = m_Last[0] = '\0';
      }
      virtual void Display()
      {
         cout << "ID: " << m_ID << endl;
         cout << "First: " << m_First << endl;
         cout << "Last: " << m_Last << endl;
      }
      void Write( int ID, char First[], char Last[] )
      {
         m_ID = ID;
         strcpy( m_First, First );
         strcpy( m_Last, Last );
      }
};
class Worker
{
   protected:
      int m_Income;
   public:
      Worker()
      {
         m_Income = 0;
      }
      void Write( int Income )
      {
         m_Income = Income;
      }
      void Display()
      {
         cout << "Income: " << m_Income << endl;
      }

};
class Instructor : public Person, public Worker
{
   protected:
      bool m_Tenured;
   public:
      Instructor()
      {
         m_Tenured = false;
      }
      void Write( int ID, char First[], char Last[], bool Tenured,
       int Salary )
      {
         Person::Write( ID, First, Last );
         Worker::Write( Salary );
         m_Tenured = Tenured;
      }
      void Display()
      {
         Person::Display();
         Worker::Display();
         cout << "Tenured: " << (m_Tenured?"Yes":"No") << endl;
      }
};
int main()
{
   Instructor i;
   i.Write( 102, "Rita", "Sharma", true, 100000 );
   i.Display();
   return 0;
}
The result of this program is the same as the level inheritance example. The Write() member function of the Instructor class is passed information for all classes. The Display() member function is called to display those values on the screen.

Here is what is displayed on the screen when you run the following program:

ID: 102
First: Rita
Last: Sharma
Income: 100000
Tenured: Yes

Multiple Inheritance Using Java



Multiple inheritance is not supported in Java. Therefore, you’ll need to use level inheritance whenever you want a class to inherit from two or more other classes. Remember that each class must pass the “is a” test. Any class that fails this test should not be used in level inheritance.

Java instead provides interfaces, which can in some ways act or seem like multiple inheritance. However, an interface is best thought of as something like a purely abstract class. That is to say, it declares the names of member functions but doesn’t actually provide any reusable code from which you can employ inheritance. If we implement an interface in a Java class, we must create all the needed code yourself for those functions. For this reason, interfaces are not really a part of inheritance.

Interfaces should really be considered a set of promises. If a class implements an interface (and therefore contains all the code needed to implement it), then other objects can communicate or work with the class via the interface.

1 comments:

thank you admin, i have really learn a lot from you, i will always visit your site to learn...............

Please try to comment if i have done well or if you have finished learning from the blog
EmoticonEmoticon

Comments system