- Java Tutorial
- Java Introduction
- Java Features
- Java Simple Program
- JVM, JDK and JRE
- Java Syntax
- Java Comments
- Java Keywords
- Java Variables
- Java Literals
- Java Separators
- Java Datatypes
- Java Operators
- Java Statements
- Java Strings
- Java Arrays
- Control Statement
- Java If
- Java If-else
- Java If-else-if
- Java Nested If
- Java Switch
- Iteration Statement
- Java For Loop
- Java For Each Loop
- Java While Loop
- Java Do While Loop
- Java Nested Loop
- Java Break/Continue
- Java Methods
- Java Methods
- Java Method Parameters
- Java Method Overloading
- Java Recursion
- Java OOPS
- Java OOPs
- Java Classes/Objects
- Java Inheritance
- Java Polymorphism
- Java Encapsulation
- Java Abstraction
- Java Modifiers
- Java Constructors
- Java Interface
- Java static keyword
- Java this keyword
- Java File Handling
- Java File
- Java Create File
- Java Read/Write File
- Java Delete File
- Java Program To
- Add Two Numbers
- Even or Odd Numbers
- Reverse a String
- Swap Two Numbers
- Prime Number
- Fibonacci Sequence
- Palindrome Strings
- Java Reference
- Java String Methods
- Java Math Methods
Java Inheritance
In Java, inheritance is a mechanism by which a class (subclass) can inherit properties and behaviors from another class (superclass). Here's an overview with examples:
Definition:
- Inheritance allows a subclass to acquire the attributes and methods of its superclass.
Syntax:
- Define a subclass by using the extends keyword followed by the superclass name.
- Example:
class Subclass extends Superclass {
// Subclass definition
}
There are different types of inheritance, including:
Single Inheritance:
- A subclass inherits from only one superclass.
- Example:
class Subclass extends Superclass {
// Subclass definition
}
Multilevel Inheritance:
- Subclasses can inherit from other subclasses, creating a chain of inheritance.
- Example:
class Animal {
// Animal class definition
}
class Dog extends Animal {
// Dog class definition
}
class Labrador extends Dog {
// Labrador class definition
}
Hierarchical Inheritance:
- Multiple subclasses inherit from the same superclass.
- Example:
class Animal {
// Animal class definition
}
class Dog extends Animal {
// Dog class definition
}
class Cat extends Animal {
// Cat class definition
}
Multiple Inheritance (Not Supported in Java):
- A subclass inherits from multiple superclasses.
- Java does not support multiple inheritance for classes to avoid the diamond problem.
- However, multiple inheritance is supported for interfaces using interface implementation.
Summary
Inheritance promotes code reuse and facilitates the creation of hierarchical relationships between classes. Understanding the different types of inheritance is essential for building modular and extensible Java applications.