×

Inheritance in C++ vs Java

Just like we inherit traits from our parents, object-oriented programming has a concept called inheritance. In terms of object-oriented programming, a class's traits and behaviours, or its data and methods, are referred to as its characteristics.

As it allows objects to take on the characteristics and behaviours of other objects, inheritance is a key component of object-oriented programming. As a result, less new code needs to be created, written, and tested every time a new programme is created. Classes inside a programme inherit from one another, creating a hierarchical connection.

Inheritance comparison in C++ and Java :

Inheritance serves the same function in Java and C++. Both languages utilise inheritance to reuse code and/or establish a "is-a" connection. The distinctions among Java and C++ that enable inheritance will be shown by the examples that follow.

1.In Java, all the classes either directly or indirectly are derived from the Object class.

As a result, there is always only one class inheritance tree in Java, with the Object Class acting as its root. When a class is created in Java, the Object Class is immediately inherited. A class that doesn't inherit from another is created as a new tree in a forest in C++, where there is a forest of classes.

The Tests class automatically derives from the Object class, as seen by the Java example.

Example :

class Tests {
	// members of the tests class
}
class Main {
	public static void main(String[] args)
	{
		Tests ts = new Tests();
		System.out.println("ts is an instance of Object: "
						+ (ts instanceof Object));
	}
}

Output :

ts is an instance of Object: true

2. In Java, it is not possible to directly access members of the grandparent class.

3. In Java, protected member access specifier has a somewhat different meaning.

In Java, even if class "Q" doesn't inherit from class "P," protected elements of class "P" are available in class "Q" of the same package (both of them must need to be in the same package).

For instance, in the programme below, protected members of P are reachable in Q.

Example :

class P {
	protected int i = 100, j = 200;
}


class Q {
	public static void main(String args[])
	{
		P p = new P();
		System.out.println(p.i + " " + p.j);
	}
}

Output :

100 200

4. For inheritance, Java utilises the 'extends' keyword.

Java does not include inheritance specifiers like public, protected, or private, in contrast to C++. Because of this, we are unable to reduce the security level of base class members in Java. If a data item is public or protected in the base class then it will stay the same in the derived class as well. Similar to C++, a derived class's private members cannot be accessed.

Contrary to C++, Java does not need us to know the inheritance rules, which combine the inheritance specifier and base class access specifier.

5) In Java, virtual methods are the default while virtual keyword is used explicitly in C++.

6) Java employs the keywords interface and abstract, respectively, for the interfaces and for the classes and methods that are abstract.

Given below is an instance of abstract class in java.

Example :

// An example of the abstract class 
abstract class theAbstractClass {  
  
    // An abstract method  
    abstract void theAbstractFun();  
  
    // A normal method  
    void func() { System.out.println("Inside the func"); }  
}  
  
public class theClass extends theAbstractClass {  
    public void theAbstractFun()  
    {  
        System.out.println("Inside the func");  
    }  
}  

Given below is an instance of java interface.

Example :

// An example of java interface.
public interface theInterface {  
  
    // theAbstractFun() is public 
    // and abstract, even if we  
    // don't use these keywords  
    void theAbstractFun();  
    // is same as public abstract void theAbstractFun()  
}  
  
// implements keyword is also used.  
public class theClass implements theInterface {  
    public void theAbstractFun()  
    {  
        System.out.println("Inside the func");  
    }  
}  

7) Java does not enable multiple inheritances, in contrast to C++.

A class can only descend from one other class. A class, though, can implement several interfaces.

8) In C++, the parent class's default constructor is automatically called, but if we wish to invoke a parent class's parameterized constructor, we must utilise the Initializer list. In Java, the parent class's default constructor is automatically invoked, similar to C++, but if we wish to execute a parameterized constructor, we must use the “super” keyword. Refer to the Java instance shown below.

Example :


class Base {
	private int B;
	Base(int p)
	{
		B = p;
		System.out.println("The Base constructor is called");
	}
}


class Derive extends Base {
	private int D;
	Derive(int p, int q)
	{
		// Parent class parameterized constructor is being called
		// The calling of parent constructor must be in the first line
		// inside the Derived class 'Derive'
		super(p);
		D = q;
		System.out.println(" The Derived constructor is called");
	}
}


class Main {
	public static void main(String[] args)
	{
		Derive objct = new Derive(10, 20);
	}
}

Output :

The Base constructor is called
The Derived constructor is called

Related Topics

Loops in C++

A loop statement in most programming languages allows us to execute a statement or a collection of statements numerous times. Control structures of programming languages vary, allowing for more complex...

6 minutes read.

Difference between Two Sets in C++

The distinction between the two sets is made up of the components that are present in the first set but absent from the second set. The function consistently duplicates the...

3 minutes read.

Print Table Using While Loop in C++

Multiplication Table In mathematics, a table is created by multiplying a certain number by all of the counting numbers, i.e., 1, 2, 3, 4, 5, 6, and so on. It is...

4 minutes read.

SET Data Structure in C++

Generally, in our home, we store food items in a fridge or kitchen efficiently to find them easily and use them. Similarly, in programming, we need to store the data...

6 minutes read.

Binary Operator Overloading in C++

The Binary Operator Overloading in the C++ programming language will be covered in this part. An operator which comprises two operands to execute a mathematical operation is termed the Binary...

6 minutes read.

Size_t Data Type in C++

In C++, the type to express the object size in bytes is defined as Size_t, an unsigned integer type offered by the standard library for describing the object's size and...

3 minutes read.

Do-While Loop Examples in C++

Before we move on the examples of Do-While loop, let’s learn little bit about the Do-While loop in C++ language. Do While loop An iterative loop that checks the condition at the...

5 minutes read.

Lambda Expression in C++

The lambda expression was introduced in C++ 11. It is used to write the inline function in C++. The code written in lambda expression cannot be reused further. The syntax...

3 minutes read.

swap() function in C++

Swap() function: swap() function in C++: swap() function is a pre-define function in c++ present in STL( Standard template library ). It is used to swap two numbers. It takes two mandatory...

6 minutes read.

Object Slicing in C++

In this article, we will learn about Object slicing. When an object from a derived class is assigned to an object from a base class in C++, these extra attributes...

3 minutes read.

Hospital Management Project in C++

The following capabilities are required to build a hospital management project: These are as follows: hospitals' names, contact information, and lists of doctors and patients. Activities Supported Hospital Data Print Patients' data to...

4 minutes read.

Hello World Program in C++

The steps for “Hello World” C++ program are as follows: Write a C++ code given below in an editor. Save the file with .cpp Compile the code using C++ compiler or using online...

3 minutes read.

Bitmasking in C++

Bitmasking is a technique that is used to access a particular bit within the data bytes. When you apply the iterative approach, this phenomenon is used. A bitmask is described...

6 minutes read.

C++ Program For FCFS (First Come First Serve)

The most basic scheduling technique is FCFS, often known as "FIFO (First In, First Out)". In this procedure, the first one is utilized and executed first, while the second one...

4 minutes read.

Armstrong Number using Do-While Loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

4 minutes read.

Reverse a String using Stack C/C++

Reverse the given string using stack. To turn "tutorialandexample" into "elpmaxednalairotut," for instance. Here is a straightforward stack-based technique for reversing strings. Algorithm: 1) Make a stack that is empty. 2) Push each character...

3 minutes read.

C++ Constructor

Constructor is a specific method in C ++ that is automatically called when an object is created. Typically, it is used to set the data members of a new object....

4 minutes read.

External merge sort in C++

External merge sort in C++ External sorting is a concept for a group of sorting algorithms capable of handling large data volumes. External sorting is needed if the information getting sorted...

9 minutes read.

C++ Date and Time

The date and time formats in C++ will be covered in this article. Because C++ lacks a proper date and time format, we must rely on the c language. The...

7 minutes read.

Implementation of a Falling Matrix in C++

In many Hollywood and Bollywood movies, we might have seen a programmer who will be referred to as a hacker all the time for some random reason which the writer...

3 minutes read.