0% found this document useful (0 votes)
16 views9 pages

Chi 2

Uploaded by

raroy67751
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views9 pages

Chi 2

Uploaded by

raroy67751
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 9

Skip to content

geeksforgeeks
Courses 90% Refund
Tutorials
Java
Practice
Contests

Sign In

Java Arrays
Java Strings
Java OOPs
Java Collection
Java 8 Tutorial
Java Multithreading
Java Exception Handling
Java Programs
Java Project
Java Collections Interview
Java Interview Questions
Java MCQs
Spring
Spring MVC
Spring Boot
Hibernate

Content Improvement Event


Share Your Experiences
Basics of Java
Variables & DataTypes in Java
Operators in Java
Packages in Java
Flow Control in Java
Loops in Java
Jump Statements in Java
Arrays in Java
Strings in Java
OOPS in Java
Constructors in Java
Inheritance & Polymorphism in Java
Inheritance in Java
Java and Multiple Inheritance
Comparison of Inheritance in C++ and Java
Polymorphism in Java
Dynamic Method Dispatch or Runtime Polymorphism in Java
Method overloading & Overiding
Abstraction & Encapsulation
Interfaces in Java
Keywords in Java
Exception Handling in Java
Collection Framework
Multi-threading in Java
Java Backend DevelopmentCourse
Comparison of Inheritance in C++ and Java
Last Updated : 03 Apr, 2023
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.

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.

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,

// 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,

// 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.

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

Three 90 Challenge is back on popular demand! After processing refunds worth INR
1CR+, we are back with the offer if you missed it the first time. Get 90% course
fee refund in 90 days. Avail now!
Want to be a master in Backend Development with Java for building robust and
scalable applications? Enroll in Java Backend and Development Live Course by
GeeksforGeeks to get your hands dirty with Backend Programming. Master the key Java
concepts, server-side programming, database integration, and more through hands-on
experiences and live projects. Are you new to Backend development or want to be a
Java Pro? This course equips you with all you need for building high-performance,
heavy-loaded backend systems in Java. Ready to take your Java Backend skills to the
next level? Enroll now and take your development career to sky highs.

https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks

81
Previous Article
Java and Multiple Inheritance
Next Article
Polymorphism in Java
Read More
Down Arrow
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
Article Tags :
Java
cpp-inheritance
java-inheritance
Practice Tags :
Java
three90RightbarBannerImg

course-img
215k+ interested Geeks
Master Java Programming - Complete Beginner to Advanced
Avail 90% Refund
course-img
214k+ interested Geeks
JAVA Backend Development - Live
Avail 90% Refund
course-img
30k+ interested Geeks
Manual to Automation Testing: A QA Engineer's Guide
Avail 90% Refund

geeksforgeeks-footer-logo
Corporate & Communications Address:- A-143, 9th Floor, Sovereign Corporate Tower,
Sector- 136, Noida, Uttar Pradesh (201305) | Registered Address:- K 061, Tower K,
Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh,
201305
GFG App on Play Store
GFG App on App Store
Company
About Us
Legal
Careers
In Media
Contact Us
Advertise with us
GFG Corporate Solution
Placement Training Program
Explore
Job-A-Thon Hiring Challenge
Hack-A-Thon
GfG Weekly Contest
Offline Classes (Delhi/NCR)
DSA in JAVA/C++
Master System Design
Master CP
GeeksforGeeks Videos
Geeks Community
Languages
Python
Java
C++
PHP
GoLang
SQL
R Language
Android Tutorial
DSA
Data Structures
Algorithms
DSA for Beginners
Basic DSA Problems
DSA Roadmap
DSA Interview Questions
Competitive Programming
Data Science & ML
Data Science With Python
Data Science For Beginner
Machine Learning Tutorial
ML Maths
Data Visualisation Tutorial
Pandas Tutorial
NumPy Tutorial
NLP Tutorial
Deep Learning Tutorial
Web Technologies
HTML
CSS
JavaScript
TypeScript
ReactJS
NextJS
NodeJs
Bootstrap
Tailwind CSS
Python Tutorial
Python Programming Examples
Django Tutorial
Python Projects
Python Tkinter
Web Scraping
OpenCV Tutorial
Python Interview Question
Computer Science
GATE CS Notes
Operating Systems
Computer Network
Database Management System
Software Engineering
Digital Logic Design
Engineering Maths
DevOps
Git
AWS
Docker
Kubernetes
Azure
GCP
DevOps Roadmap
System Design
High Level Design
Low Level Design
UML Diagrams
Interview Guide
Design Patterns
OOAD
System Design Bootcamp
Interview Questions
School Subjects
Mathematics
Physics
Chemistry
Biology
Social Science
English Grammar
Commerce
Accountancy
Business Studies
Economics
Management
HR Management
Finance
Income Tax
Databases
SQL
MYSQL
PostgreSQL
PL/SQL
MongoDB
Preparation Corner
Company-Wise Recruitment Process
Resume Templates
Aptitude Preparation
Puzzles
Company-Wise Preparation
Companies
Colleges
Competitive Exams
JEE Advanced
UGC NET
UPSC
SSC CGL
SBI PO
SBI Clerk
IBPS PO
IBPS Clerk
More Tutorials
Software Development
Software Testing
Product Management
Project Management
Linux
Excel
All Cheat Sheets
Recent Articles
Free Online Tools
Typing Test
Image Editor
Code Formatters
Code Converters
Currency Converter
Random Number Generator
Random Password Generator
Write & Earn
Write an Article
Improve an Article
Pick Topics to Write
Share your Experiences
Internships
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By
using our site, you acknowledge that you have read and understood our Cookie Policy
& Privacy Policy
Got It !
Lightbox

You might also like