Inheritance, polymorphism, and encapsulation

codezone
2 min readMar 24, 2024

Java is an object-oriented programming language that supports fundamental principles of object-oriented programming, including inheritance, polymorphism, and encapsulation. In this article, we’ll explain the concepts of inheritance, polymorphism, and encapsulation in Java, along with examples demonstrating their usage.

Inheritance

Inheritance is a mechanism in which a class can inherit properties (fields and methods) from another class. In Java, inheritance is achieved using the extends keyword. Here's an example:

// Superclass
class Animal {
void eat() {
System.out.println("The animal eats.");
}
}

// Subclass
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}

In the example above, the Animal class represents a superclass, while the Dog class inherits from the Animal class.

Polymorphism

Polymorphism is the ability of an object to take on different forms. In Java, polymorphism is achieved through inheritance and method overriding. Here’s an example:

// Superclass
class Animal {
void makeSound() {
System.out.println("Animal makes a sound.");
}
}

// Subclass
class Dog extends Animal {
void makeSound() {…

--

--