Advanced Java OOP: Day 8 — Deep Dive into Encapsulation and Inheritance

Krishna
Javarevisited
Published in
2 min readJan 24, 2024

Welcome to Day 8 of the 30-Day Java Challenge! Building on our introduction to Object-Oriented Programming (OOP), today we focus on two core principles of OOP in Java: Encapsulation and Inheritance.

Encapsulation in Java

Encapsulation is about bundling the data (variables) and the methods that operate on the data into a single unit or class. It also restricts direct access to some of the object's components, which is a means of preventing accidental interference and misuse of the methods and data.

Implementing Encapsulation

  • Private Variables: Make the variables of a class private, so they cannot be accessed directly from outside the class.
  • Public Methods: Provide public setter and getter methods to modify and view the variable values.

Example: Encapsulated Class

Inheritance in Java

Inheritance allows a new class to inherit properties and methods from an existing class. The class that inherits is called a subclass, and the class it inherits from is called a superclass.

Implementing Inheritance

  • extends Keyword: Use the extends keyword to inherit from a class.

Example: Inheritance

Practice Example 1: Enhanced Employee Class

Practice Example 2: Shape Hierarchy

With Day 8, we’ve delved deeper into the principles of Encapsulation and Inheritance in Java OOP. Understanding these concepts is crucial for creating efficient and secure Java applications. Join me on Day 9, where we’ll explore Polymorphism in Java.

Happy Coding!

--

--

Krishna
Javarevisited

Committed to learning and sharing knowledge, I write articles and teach about the latest in tech and software development. I love travelling and photography!