Java FAQ: Top Questions
11. What is inheritance in Java?
Inheritance is an object-oriented programming (OOP) mechanism in Java that allows a class (subclass or derived class) to inherit fields and methods from another class (superclass or base class). It promotes code reusability and establishes a hierarchical relationship between classes.
Key points about inheritance:
-
Extends Keyword:
A subclass uses the
extends
keyword to inherit from a superclass. - Single Inheritance: Java supports single inheritance, meaning a class can extend only one superclass (unlike multiple inheritance in C++).
-
Access to Members:
Subclasses inherit non-private members (fields, methods) of the superclass, subject to access modifiers (
protected
,public
). - Super Keyword: Used to call the superclass’s constructor or methods.
-
Object Class:
All Java classes implicitly extend
java.lang.Object
, the root of the class hierarchy.