Encapsulation in OOP - Java

🚀 𝗝𝗮𝘃𝗮 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗣𝗿𝗲𝗽 – Day 4 4 Pillers of OOP - 1st 𝐄𝐧𝐜𝐚𝐩𝐬𝐮𝐥𝐚𝐭𝐢𝐨𝐧 🔐 𝐄𝐧𝐜𝐚𝐩𝐬𝐮𝐥𝐚𝐭𝐢𝐨𝐧 (𝐎𝐎𝐏 𝐂𝐨𝐧𝐜𝐞𝐩𝐭) Encapsulation is the concept of 𝐰𝐫𝐚𝐩𝐩𝐢𝐧𝐠 𝐝𝐚𝐭𝐚 (variables) and 𝐦𝐞𝐭𝐡𝐨𝐝𝐬 (functions) into a single unit, usually a class, and 𝐫𝐞𝐬𝐭𝐫𝐢𝐜𝐭𝐢𝐧𝐠 𝐝𝐢𝐫𝐞𝐜𝐭 𝐚𝐜𝐜𝐞𝐬𝐬 to some of the object's components. 💡 𝐈𝐧 𝐒𝐢𝐦𝐩𝐥𝐞 𝐖𝐨𝐫𝐝𝐬 Encapsulation means: 👉 𝐃𝐚𝐭𝐚 𝐡𝐢𝐝𝐢𝐧𝐠 + 𝐜𝐨𝐧𝐭𝐫𝐨𝐥𝐥𝐞𝐝 𝐚𝐜𝐜𝐞𝐬𝐬 You don’t allow direct access to variables. Instead, you use methods to access and update them. 🔍 𝐊𝐞𝐲 𝐏𝐨𝐢𝐧𝐭𝐬 • Variables are declared as 𝐩𝐫𝐢𝐯𝐚𝐭𝐞 • Access is given using 𝐩𝐮𝐛𝐥𝐢𝐜 𝐠𝐞𝐭𝐭𝐞𝐫 & 𝐬𝐞𝐭𝐭𝐞𝐫 𝐦𝐞𝐭𝐡𝐨𝐝𝐬 • Helps in 𝐝𝐚𝐭𝐚 𝐡𝐢𝐝𝐢𝐧𝐠 𝐚𝐧𝐝 𝐬𝐞𝐜𝐮𝐫𝐢𝐭𝐲 • Allows 𝐯𝐚𝐥𝐢𝐝𝐚𝐭𝐢𝐨𝐧 before updating values 🚀 𝐀𝐝𝐯𝐚𝐧𝐭𝐚𝐠𝐞𝐬 ✔ Protects data from unauthorized access ✔ Improves code security ✔ Provides controlled access ✔ Makes code flexible and maintainable 🤔 𝐂𝐨𝐦𝐦𝐨𝐧 𝐃𝐨𝐮𝐛𝐭 At first glance it feels like: 👉 “If I can set value using setter, how is it different from public?” 📊 𝐃𝐢𝐟𝐟𝐞𝐫𝐞𝐧𝐜𝐞 𝐏𝐮𝐛𝐥𝐢𝐜 𝐕𝐚𝐫𝐢𝐚𝐛𝐥𝐞 ➡ Direct access ➡ No validation ➡ Unsafe ➡ Hard to maintain 𝐏𝐫𝐢𝐯𝐚𝐭𝐞 + 𝐒𝐞𝐭𝐭𝐞𝐫 ➡ Controlled access ➡ Validation possible ➡ Safe ➡ Easy to update logic 🧪 𝐄𝐱𝐚𝐦𝐩𝐥𝐞 (𝐏𝐫𝐚𝐜𝐭𝐢𝐜𝐚𝐥 𝐔𝐧𝐝𝐞𝐫𝐬𝐭𝐚𝐧𝐝𝐢𝐧𝐠) See below ScreenShot 🧠 𝐂𝐨𝐧𝐜𝐞𝐩𝐭 𝐂𝐥𝐚𝐫𝐢𝐭𝐲 👉 myName in class X ❌ Cannot be modified directly (no setter) → 𝐅𝐮𝐥𝐥𝐲 𝐩𝐫𝐨𝐭𝐞𝐜𝐭𝐞𝐝 👉 a in class X ✅ Can be modified using setter → 𝐂𝐨𝐧𝐭𝐫𝐨𝐥𝐥𝐞𝐝 𝐚𝐜𝐜𝐞𝐬𝐬 👉 myName in class Y ✅ Public → can be modified directly → 𝐍𝐨 𝐜𝐨𝐧𝐭𝐫𝐨𝐥 (unsafe) 🔥 𝐊𝐞𝐲 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Encapsulation is not about blocking access completely, 👉 it’s about 𝐜𝐨𝐧𝐭𝐫𝐨𝐥𝐥𝐢𝐧𝐠 𝐡𝐨𝐰 𝐚𝐜𝐜𝐞𝐬𝐬 𝐢𝐬 𝐠𝐢𝐯𝐞𝐧. 👉 Encapsulation ensures that data is accessed and modified only through controlled methods, improving security and maintainability. #Java #OOP #Encapsulation #Programming #CodingInterview #Developers #P_Pranjali #Java_Day4 #SoftwareDevelopment

  • graphical user interface, text, application, email

#Java #OOP #Encapsulation #Programming #CodingInterview #Developers #P_Pranjali #Java_Day4 #SoftwareDevelopment

Like
Reply

To view or add a comment, sign in

Explore content categories