C++ Inheritance in C++ vs. Java
Inheritance is a fundamental concept in object-oriented programming that allows a class to inherit properties and behaviors from another class. This guide will compare the syntax, examples, output, explanations, use cases, important points, and provide a summary of inheritance in C++ and Java.
Syntax
C++
class Base {
public:
void display() {
std::cout << "Base class display\n";
}
};
class Derived : public Base {
public:
void show() {
std::cout << "Derived class show\n";
}
};
Java
class Base {
void display() {
System.out.println("Base class display");
}
}
class Derived extends Base {
void show() {
System.out.println("Derived class show");
}
}
Example
Let's consider an example where the derived class inherits from the base class and extends its functionality.
C++
int main() {
Derived derivedObj;
derivedObj.display();
derivedObj.show();
return 0;
}
Java
public class Main {
public static void main(String[] args) {
Derived derivedObj = new Derived();
derivedObj.display();
derivedObj.show();
}
}
Output
The output for both C++ and Java examples will display:
Base class display
Derived class show
Explanation
- In C++, the
public
keyword specifies the access specifier for inheritance. - In Java, the
extends
keyword is used for inheritance. - The derived class inherits the members (methods and properties) of the base class.
Use
- Code Reusability: Inheritance allows the reuse of code from existing classes.
- Polymorphism: Enables the use of derived class objects where base class objects are expected.
Important Points
- In C++, default access specifier for members of a class is
private
, while in Java, it isdefault
(package-private). - C++ supports multiple inheritance, while Java supports only single inheritance.
Summary
Inheritance is a powerful mechanism in both C++ and Java for creating a hierarchy of classes and promoting code reuse. While the syntax for inheritance is somewhat similar in both languages, there are subtle differences, such as the use of access specifiers. Understanding these differences is crucial when transitioning between C++ and Java or when working with projects in both languages. Both languages provide a solid foundation for building object-oriented systems with effective use of inheritance.