AI May 15, 2023 5 min read

Module 13: Encapsulation

BR

Bhargava Ram Pantina

Web Developer & AI Enthusiast

🔐 What is Encapsulation?

Encapsulation is the practice of wrapping data (variables) and methods that operate on the data into a single unit called a class. It helps protect the internal state of an object and restricts direct access to some of its components.

This is achieved using:

  • Private variables
  • Public getter and setter methods

💡 Example of Encapsulation

                    class Person {
                        private String name;
                        private int age;
                    
                        public String getName() {
                            return name;
                        }
                    
                        public void setName(String name) {
                            this.name = name;
                        }
                    
                        public int getAge() {
                            return age;
                        }
                    
                        public void setAge(int age) {
                            if(age > 0) {
                                this.age = age;
                            }
                        }
                    
                        public static void main(String[] args) {
                            Person p = new Person();
                            p.setName("John");
                            p.setAge(25);
                            System.out.println("Name: " + p.getName());
                            System.out.println("Age: " + p.getAge());
                        }
                    }
                    

Here, the internal variables name and age are protected and accessed only via public methods.

Artificial Intelligence Web Development Technology Trends Machine Learning UX Design

Share this article

About the Author

BR

Bhargava Ram Pantina

Bhargava Ram is a web developer and AI enthusiast with over 8 years of experience in the tech industry. He specializes in creating innovative web solutions that leverage the latest technologies to solve real-world problems.

Related Articles

AI Mar 15, 2023

Implementing ChatGPT in Your Web Application: A Step-by-Step Tutorial

Learn how to integrate OpenAI's ChatGPT into your web application to create intelligent chatbots and enhance user interactions.

Read More →
Web Development Apr 22, 2023

Building Accessible Web Forms: A Complete Guide

Learn how to create web forms that are accessible to all users, including those with disabilities. This comprehensive guide covers ARIA attributes, keyboard navigation, and more.

Read More →

Subscribe to My Newsletter

Get the latest articles and resources delivered straight to your inbox.

No spam, just valuable content. Unsubscribe anytime.