# Comparison of Inheritance in C++ and Java ....Part-1: The - TopicsExpress



          

# Comparison of Inheritance in C++ and Java ....Part-1: The purpose of inheritance is same in C++ and Java. Inheritance is used in both languages for reusing code and/or creating is-a relationship. There are following differences in the way both languages 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 Object class is root of the tree. In Java, if we create a class that doesn’t inherit from any class then it automatically inherits from Object class . In C++, there is forest of classes; when we create a class that doesn’t inherit from anything, we create a new tree in forest. Following Java example shows that Test class automatically inherits from Object class. 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. 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 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. // filename 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); } } 4) Java uses extends keyword for inheritence. Unlike C++, Java doesn’t provide an inheritance specifier like public, protected or private. Therefore, we cannot change the protection level of members of base class in Java, if some data member is public or protected in base class then it remains public or protected in derived class. Like C++, private members of base class are not accessible in derived class. Unlike C++, in Java, we don’t have to remember those rules of inheritance which are combination of base class access specifier and inheritance specifier. 5) In Java, methods are virtual by default. In C++, we explicitly use virtual keyword.
Posted on: Fri, 14 Nov 2014 04:22:17 +0000

Trending Topics



0px; min-height:30px;"> Rest during a workout is not wasted time. In order to get the most
Psalm 92:12-14, The righteous will flourish like a palm tree, they

Recently Viewed Topics




© 2015