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.
Directly accessing Grandparent’s member in Java: Predict the output of following Java program.
Predict the output of following Java programs.
Difficulty Level: Rookie Predict the output of following Java Programs.
In Java, methods and data members of a class/interface can have one of the following four access specifiers. The access specifiers are listed according to their restrictiveness order.
Unlike C++, Java supports a special block, called static block (also called static clause) which can be used for static initializations of a class.
In C++ and Java, functions can not be overloaded if they differ only in the return type.
In Java, all methods in an interface are public even if we do not specify public with method names. Also, data fields are public static final even if we do not mention it with fields names. Therefore, data fields must be initialized.
In Java, it is compiler error to give more restrictive access to a derived class function which overrides a base class function.
In Java, constructor of base class with no argument gets automatically called in derived class constructor. For example, output of following program is:
Unlike C++, arrays are first class objects in Java. For example, in the following program, size of array is accessed using length which is a member of arr object.