Inheritance in C++ vs Java


In C++ and Java, there are the concept of Inheritance. The inheritance properties are used to reuse the code and also make a relationship between two objects. Here we will see some basic differences between inheritance in C++ and inheritance in Java.

  • In Java, all of the classes are extending the Object class. So there is always a single level inheritance tree of classes. The object class is present at the root of the tree. Let us check this is true or not using a simple code.

Example

//This is present in the different file named MyClass.java
public class MyClass {
   MyClass() {
      System.out.println("This is constructor of MyClass.");
   }
}
//This is present the different file named Test.Java
public class Test {
   public static void main(String[] args) {
      MyClass obj = new MyClass();
      System.out.println("obj is an instance of Object: " + (obj instanceof Object));
   }
}

Output

This is constructor of MyClass.
obj is an instance of Object: true
  • In Java, members of the grandparent classes can bot be accessed directly.

  • The protected visibility is little bit different in Java compared to C++. In Java the protected members of the base class are accessible from the another class of the same package, even if that class is not derived from the base class. Here the protected member of MyClass can be accessible from Test.

Example

//This is present in the different file named MyClass.java
public class MyClass {
   protected int x = 10;
   protected int y = 20;
}
//This is present the different file named Test.Java
public class Test {
   public static void main(String[] args) {
      MyClass obj = new MyClass();
      System.out.println("x is: " + obj.x + " y is: " + obj.y);
   }
}

Output

x is: 10 y is: 20
  • In Java, we java to use the extends keyword for inheritance. In C++, we can determine the visibility of the inheritance like public, protected and private, but here we cannot change the visibility. So if some member is public or protected in base class, they will also be public or protected in derived class also.

  • In java all methods are virtual by default. In C++, we have to specify the virtual keyword.

  • In C++, we can use the multiple inheritance. In Java, we cannot create multiple inheritance directly. To reduce ambiguity, java supports interfaces to get the effect of multiple inheritance. The interfaces are purely abstract base class, where no functions are complete, so there is no ambiguity.

Updated on: 30-Jul-2019

973 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements