×

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

C++ References

C++ References An alias is a reference variable that is another name for a variable already in existence. If a relation is initialized with a variable, it is possible to use...

3 minutes read.

Input Iterators in C++

What are input iterators? Input iterators are used in sequence for carrying out input operations where each value is read-only. It is pointed by the iterator and further incremented. All the iterators...

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.

Type difference of Character literals in C VS C++

Character literals in C: In C, a character literal is represented by a single character enclosed in single quotes, such as 'a' or 'b'. It is of type int. This means...

5 minutes read.

How to Use Getline in C++

What is getline in C++? Similar to the cin function, which allows the programmer to take input from the user getline() function also takes input from the user. But in this...

4 minutes read.

Hexadecimal to Decimal in C++

In computers, hexadecimal numbers are represented with base 16 and decimal numbers are represented with base 10 and values 0-9, whereas hexadecimal numbers have digits ranging from 0 to 15,...

3 minutes read.

Sizeof() Operators in C++

sizeof() Operators in C++ The sizeof() operator in C++ defines the size of variables, constants, or data types. It is a unique operator that manipulates other operators and returns the size...

4 minutes read.

C++ Global Variable

In C++, a global variable is a variable that is defined outside of any function or class and can be accessed by any function or class in the program. Global...

4 minutes read.

C++ find missing in the second array

Given two arrays A and B of sizes n and m. Find the elements from array A that are not present in array B. Example Input : a[] = {1, 2, 3, 5,...

3 minutes read.

Passing a Vector to a function in C++

A pointer is sent to the function when we feed it an array. However, there are two ways to pass a vector: Pass by Value Pass by Reference A copy of a vector...

3 minutes read.

Palindrome Number Program in C++

A palindrome number is one that is the same when it is reversed. Palindrome numbers include 22, 33, 44, 55, 66, 77, 88, and 99. Algorithm for Palindrome Numbers Get the user's...

4 minutes read.

How to enter a name in C++

A name is a string or array of characters or letters. The string is one of the most helpful data types offered by the C++ library. A string helps the...

4 minutes read.

Char Array to String in C++

Regardless of the programming language you use, data structure is critical to the success of your project. Although each programming language has its own collection of data structures, C++ contains a...

4 minutes read.

Add two numbers represented by two arrays in C++

The array stores a number in such a way that each digit of the number is represented by an array element. As an example, The array number 147 is 1,4,7. To add...

3 minutes read.

Dynamic _Cast in C++

C++ is one of the most powerful programming languages. We can write object-oriented and structured programming with the help of C++. In this article, we will learn about the dynamic...

3 minutes read.

C++ Iterators

What are iterators ? Iterators are among the four foundations of the C++ Standard Template Library, also known as the STL. The memory address of the STL container classes is pointed...

15 minutes read.

Diamond Pattern using While-loop in C++

What is while Loop? A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the...

5 minutes read.

Vector resize() in C++

Vector resize() in C++ Vectors are called dynamic arrays and can automatically adjust their size when a component is added or deleted. This container is used for storage. The function modifies the...

3 minutes read.

Bit Manipulation in C++

The high-level language in which we communicate is not understood by the computer. As a result, there existed a standard mechanism for understanding any instruction sent to the computer. At...

5 minutes read.

C++ If

C++ Control Statement C++ control statement or decision-making statement is used to control the flow of program statement according to condition applied. C++ if Control Statement An if control statement in C++ is used to...

2 minutes read.