The Wayback Machine - https://web.archive.org/web/20241118102119/https://www.geeksforgeeks.org/comparison-of-inheritance-in-c-and-java/
Open In App

Comparison of Inheritance in C++ and Java

Last Updated : 03 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The purpose of inheritance is the same in C++ and Java. Inheritance is used in both languages for reusing code and/or creating an ‘is-a’ relationship. The following examples will demonstrate the differences between Java and C++ that provide support for inheritance. 

1) In Java, all classes inherit from the Object class directly or indirectly. Therefore, there is always a single inheritance tree of classes in Java, and the Object Class is the root of the tree. In Java, when creating a class it automatically inherits from the Object Class. In C++ however, there is a forest of classes; when we create a class that doesn’t inherit from another, we create a new tree in a forest. 

Following the Java, example shows that the Test class automatically inherits from the Object class. 

Java




class Test {
    // members of test
}
class Main {
    public static void main(String[] args)
    {
        Test t = new Test();
        System.out.println("t is instanceof Object: "
                           + (t instanceof Object));
    }
}


Output

t is instanceof Object: true

2) In Java, members of the grandparent class are not directly accessible.  (Refer to this article for more details). 

3) The meaning of protected member access specifier is somewhat different in Java. In Java, protected members of a class “A” are accessible in other class “B” of the same package, even if B doesn’t inherit from A (they both have to be in the same package).

For example, in the following program, protected members of A are accessible in B. 

Java




class A {
    protected int x = 10, y = 20;
}
 
class B {
    public static void main(String args[])
    {
        A a = new A();
        System.out.println(a.x + " " + a.y);
    }
}


Output

10 20

4) Java uses ‘extends’ keywords for inheritance. Unlike C++, Java doesn’t provide an inheritance specifier like public, protected, or private. Therefore, we cannot change the protection level of members of the base class in Java, if some data member is public or protected in the base class then it remains public or protected in the derived class. Like C++, private members of a base class are not accessible in a derived class. 

Unlike C++, in Java, we don’t have to remember those rules of inheritance which are a combination of base class access specifier and inheritance specifier. 

5) In Java, methods are virtual by default. In C++, we explicitly use virtual keywords (Refer to this article for more details).
6) Java uses a separate keyword interface for interfaces and abstract keywords for abstract classes and abstract functions.

Following is a Java abstract class example,

Java




// An abstract class example
abstract class myAbstractClass {
 
    // An abstract method
    abstract void myAbstractFun();
 
    // A normal method
    void fun() { System.out.println("Inside My fun"); }
}
 
public class myClass extends myAbstractClass {
    public void myAbstractFun()
    {
        System.out.println("Inside My fun");
    }
}


Following is a Java interface example, 
 

Java




// An interface example
public interface myInterface {
   
    // myAbstractFun() is public
     // and abstract, even if we
    // don't use these keywords
    void myAbstractFun();
    // is same as public abstract void myAbstractFun()
}
 
// Note the implements keyword also.
public class myClass implements myInterface {
    public void myAbstractFun()
    {
        System.out.println("Inside My fun");
    }
}


7) Unlike C++, Java doesn’t support multiple inheritances. A class cannot inherit from more than one class. However, A class can implement multiple interfaces.
8) In C++, the default constructor of the parent class is automatically called, but if we want to call a parameterized constructor of a parent class, we must use the Initializer list. Like C++, the default constructor of the parent class is automatically called in Java, but if we want to call parameterized constructor then we must use super to call the parent constructor. See the following Java example.

Java




class Base {
    private int b;
    Base(int x)
    {
        b = x;
        System.out.println("Base constructor called");
    }
}
 
class Derived extends Base {
    private int d;
    Derived(int x, int y)
    {
        // Calling parent class parameterized constructor
        // Call to parent constructor must be the first line
        // in a Derived class
        super(x);
        d = y;
        System.out.println("Derived constructor called");
    }
}
 
class Main {
    public static void main(String[] args)
    {
        Derived obj = new Derived(1, 2);
    }
}


Output

Base constructor called
Derived constructor called


Previous Article
Next Article

Similar Reads

Comparison of Exception Handling in C++ and Java
Both languages use to try, catch and throw keywords for exception handling, and their meaning is also the same in both languages. Following are the differences between Java and C++ exception handling: Java C++ Only throwable objects can be thrown as exceptions.All types can be thrown as exceptions.We can catch Exception objects to catch all kinds o
4 min read
Comparison of static keyword in C++ and Java
Static keyword is used for almost the same purpose in both C++ and Java. There are some differences though. This post covers similarities and differences of static keyword in C++ and Java. Similarities between C++ and Java for Static KeywordStatic data members can be defined in both languages.Static member functions can be defined in both languages
6 min read
Comparison of double and float primitive types in Java
Consider the following two codes in Java: Java Code // This program prints true class Geeksforgeeks { public static void main(String args[]) { float f = 5.25f; double d = 5.25 System.out.println(f == d); } } Output true Java Code // But this program prints false. class Geeksforgeeks { public static void main(String args[]) { float f = 5.1f; double
2 min read
Java 11 - Features and Comparison
Every 6 months, Oracle releases new Java versions. The September Java 11 version is already making a lot of buzz in the computer science world even before it was released by declaring that from now on Java is gonna be paid for commercial use. The following articles will show important features, enhancements, and deprecated features about JDK 11. Im
5 min read
Comparison of boolean data type in C++ and Java
The Boolean data type is one of the primitive data types in both C++ and Java. Although, it may seem to be the easiest of all the data types, as it can have only two values - true or false, but it surely is a tricky one as there are certain differences in its usage in both Java and C++, which if not taken care, can result in an error. The differenc
5 min read
Java and Multiple Inheritance
Multiple Inheritance is a feature of an object-oriented concept, where a class can inherit properties of more than one parent class. The problem occurs when there exist methods with the same signature in both the superclasses and subclass. On calling the method, the compiler cannot determine which class method to be called and even on calling which
6 min read
Difference between Inheritance and Composition in Java
Inheritance: When we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. In doing this, we can reuse the fields and methods of the existing class without having to write them ourself. A subclass inherits all the members (fields, methods, and nested
3 min read
Difference between Inheritance and Interface in Java
Java is one of the most popular and widely used programming languages. Java has been one of the most popular programming languages for many years. Java is Object Oriented. However, it is not considered as a pure object-oriented as it provides support for primitive data types (like int, char, etc). In this article, we will understand the difference
3 min read
Illustrate Class Loading and Static Blocks in Java Inheritance
Class loading means reading .class file and store corresponding binary data in Method Area. For each .class file, JVM will store corresponding information in Method Area. Now incorporating inheritance in class loading. In java inheritance, JVM will first load and initialize the parent class and then it loads and initialize the child class. Example
3 min read
Interfaces and Inheritance in Java
A class can extend another class and can implement one and more than one Java interface. Also, this topic has a major influence on the concept of Java and Multiple Inheritance. Note: This Hierarchy will be followed in the same way, we cannot reverse the hierarchy while inheritance in Java. This means that we cannot implement a class from the interf
7 min read
Inheritance and Constructors in Java
Constructors in Java are used to initialize the values of the attributes of the object serving the goal to bring Java closer to the real world. We already have a default constructor that is called automatically if no constructor is found in the code. But if we make any constructor say parameterized constructor in order to initialize some attributes
3 min read
Comparison of Java with other programming languages
Java is one of the most popular and widely used programming language and platform. A platform is an environment that helps to develop and run programs written in any programming language. Java is fast, reliable and secure. From desktop to web applications, scientific supercomputers to gaming consoles, cell phones to the Internet, Java is used in ev
4 min read
Brief Overview & Comparison of Object-Oriented Programming from C to Java
In this article, you will get the ability to think how really OOP works in Java through C. Through C, you will understand the concept of Polymorphism, Inheritance, Encapsulation, Class, Objects, etc. As you also know C language don't support OOP, but we can understand the concept behind it by defining a fine structure as a Class and Creating its Id
3 min read
Comparison of Autoboxed Integer objects in Java
When we assign an integer value to an Integer object, the value is autoboxed into an Integer object. For example the statement "Integer x = 10" creates an object 'x' with value 10. Following are some interesting output questions based on comparison of Autoboxed Integer objects. Predict the output of following Java Program // file name: Main.java pu
2 min read
Image Processing in Java - Comparison of Two Images
Prerequisites: Image Processing in Java - Read and WriteImage Processing In Java - Get and Set PixelsImage Processing in Java - Colored Image to Grayscale Image ConversionImage Processing in Java - Colored Image to Negative Image ConversionImage Processing in Java - Colored to Red Green Blue Image ConversionImage Processing in Java - Colored Image
4 min read
Java | Inheritance | Question 1
Output of following Java Program? class Base { public void show() { System.out.println("Base::show() called"); } } class Derived extends Base { public void show() { System.out.println("Derived::show() called"); } } public class Main { public static void main(String[] args) { Base b = new Derived();; b.show(); } } (A) Derived::sh
1 min read
Java | Inheritance | Question 2
class Base { final public void show() { System.out.println("Base::show() called"); } } class Derived extends Base { public void show() { System.out.println("Derived::show() called"); } } class Main { public static void main(String[] args) { Base b = new Derived();; b.show(); } } (A) Base::show() called (B) Derived::show() called
1 min read
Java | Inheritance | Question 3
Java Code class Base { public static void show() { System.out.println("Base::show() called"); } } class Derived extends Base { public static void show() { System.out.println("Derived::show() called"); } } class Main { public static void main(String[] args) { Base b = new Derived(); b.show(); } } (A) Base::show() called (B) Deriv
1 min read
Java | Inheritance | Question 4
Which of the following is true about inheritance in Java? 1) Private methods are final. 2) Protected members are accessible within a package and inherited classes outside the package. 3) Protected methods are final. 4) We cannot override private methods. (A) 1, 2 and 4 (B) Only 1 and 2 (C) 1, 2 and 3 (D) 2, 3 and 4 Answer: (A) Explanation: See http
1 min read
Java | Inheritance | Question 5
Output of following Java program? class Base { public void Print() { System.out.println("Base"); } } class Derived extends Base { public void Print() { System.out.println("Derived"); } } class Main{ public static void DoPrint( Base o ) { o.Print(); } public static void main(String[] args) { Base x = new Base(); Base y = new Deri
1 min read
Java | Inheritance | Question 9
Predict the output of following program. Note that foo() is public in base and private in derived. class Base { public void foo() { System.out.println("Base"); } } class Derived extends Base { private void foo() { System.out.println("Derived"); } } public class Main { public static void main(String args[]) { Base b = new Derived
1 min read
Java | Inheritance | Question 7
Which of the following is true about inheritance in Java. 1) In Java all classes inherit from the Object class directly or indirectly. The Object class is root of all classes. 2) Multiple inheritance is not allowed in Java. 3) Unlike C++, there is nothing like type of inheritance in Java where we can specify whether the inheritance is protected, pu
1 min read
Java | Inheritance | Question 8
Predict the output of following Java Program // filename Main.java class Grandparent { public void Print() { System.out.println("Grandparent's Print()"); } } class Parent extends Grandparent { public void Print() { System.out.println("Parent's Print()"); } } class Child extends Parent { public void Print() { super.super.Print();
1 min read
Java | Inheritance | Question 9
final class Complex { private final double re; private final double im; public Complex(double re, double im) { this.re = re; this.im = im; } public String toString() { return "(" + re + " + " + im + "i)"; } } class Main { public static void main(String args[]) { Complex c = new Complex(10, 15); System.out.println(
1 min read
Output of Java program | Set 23 (Inheritance)
Prerequisite: Inheritance in Java 1) What is the output of the following program? Java Code public class A extends B { public static String sing() { return "fa"; } public static void main(String[] args) { A a = new A(); B b = new A(); System.out.println(a.sing() + " " + b.sing()); } } class B { public static String sing() { retu
3 min read
Resolving Conflicts During Multiple Inheritance in Java
A class can implement multiple interfaces in java, but what if the implemented multiple default interfaces have default methods with the same signatures? Then in the implementing class, which of the default implementations would be invoked from the several parent interfaces. Java 8 designers have been thinking about this conflict and have specified
5 min read
Java - Exception Handling With Constructors in Inheritance
Java provides a mechanism to handle exceptions. To learn about exception handling, you can refer to exceptions in java. In this article, we discuss exception handling with constructors when inheritance is involved. In Java, if the constructor of the parent class throws any checked exception, then the child class constructor can throw the same excep
7 min read
What is the Need of Inheritance in Java?
Inheritance, as we have all heard is one of the most important features of Object-Oriented Programming Languages whether it is Java, C++, or any other OOP language. But what is the need for Inheritance? Why is it so an important concept Inheritance can be defined as a mechanism by which one object can acquire all the properties (i.e. data members)
6 min read
How to Implement Multiple Inheritance by Using Interfaces in Java?
Multiple Inheritance is a feature of an object-oriented concept, where a class can inherit properties of more than one parent class. The problem occurs when methods with the same signature exist in both the superclasses and subclass. On calling the method, the compiler cannot determine which class method to be called and even on calling which class
2 min read
Using final with Inheritance in Java
Prerequisite - Overriding in java, Inheritance final is a keyword in java used for restricting some functionalities. We can declare variables, methods, and classes with the final keyword. Using final with inheritance During inheritance, we must declare methods with the final keyword for which we are required to follow the same implementation throug
4 min read
Practice Tags :
three90RightbarBannerImg