📘 Day 34 – Java Concepts: Access Modifiers & Method Overriding Today I revised some important Java concepts that help in writing secure and flexible code. 🔹 Access Modifiers in Java Access modifiers define the visibility of classes, methods, and variables. • public – Accessible from anywhere • protected – Accessible within the same package and subclasses • default – Accessible only within the same package • private – Accessible only within the same class 📊 Accessibility (Summary): ✔ Inside class → All accessible ✔ Same package → public, protected, default ✔ Subclass (different package) → public, protected ✔ Outside package → only public 🔹 Rules of Method Overriding • Method name must be the same • Parameters must be the same • Return type must be same or covariant • Access modifier cannot be more restrictive 🔹 Covariant Return Type A child class method can return a subtype of the parent method’s return type. 🔹 Final Keyword • final variable → constant • final method → cannot be overridden • final class → cannot be inherited 💡 Understanding these concepts improves code reusability, security, and maintainability. #Java #OOP #Programming #CodingJourney #Day34 #Developers
Java Access Modifiers & Method Overriding Rules
More Relevant Posts
-
Mastering Java methods, constructors, and overloading is key to writing clean, flexible code. 🚀 These fundamentals help you reuse logic, initialize objects, and handle multiple inputs efficiently. https://lnkd.in/d9uvNnJP #Java #OOP #Programming
To view or add a comment, sign in
-
Still writing boilerplate DTO classes in Java? Java Records make that feel outdated. Introduced as a preview in Java 14 and officially released in Java 16, Records were designed to solve one common problem in Java: Too much code for simple data-holding classes. What used to take constructors, getters, equals(), hashCode(), and toString() can now be written in one clean line: public record UserDTO(String name, String email) {} Why does this matter in Spring Boot? Because Records are perfect for: - Request and response DTOs - Validation models - Projection classes - Configuration properties What problem do they solve? They remove boilerplate, improve readability, and give you immutable data classes by default. Cleaner code. Less repetition. Better maintainability. One thing to remember: Records are excellent for DTOs, but not a good fit for JPA entities. Modern Java is evolving and Records are one feature every Spring Boot developer should know.
To view or add a comment, sign in
-
💡 Java Exception Handling — Are You Losing Important Errors? 🚨 While learning Java, I came across something very important: 👉 Chained Exceptions 🔹 What is a Chained Exception? A chained exception means linking one exception with another, so we don’t lose the original error. 🔴 Without Chaining (Bad Practice) try { int a = 10 / 0; } catch (Exception e) { throw new RuntimeException("Something went wrong"); } ❌ Output: RuntimeException: Something went wrong 👉 Problem: Original error (/ by zero) is LOST ❌ 🟢 With Chaining (Best Practice) try { int a = 10 / 0; } catch (Exception e) { throw new RuntimeException("Something went wrong", e); } ✅ Output: RuntimeException: Something went wrong Caused by: ArithmeticException: / by zero 👉 Now we get the complete error story ✅ 🔍 Why is this important? ✔ Helps in debugging ✔ Keeps original error intact ✔ Used in real-world backend systems ✔ Makes logs more meaningful 🧠 Golden Rule: 👉 Always pass the original exception: throw new Exception("Message", e); 💬 Simple Analogy: Without chaining → "Something broke" ❌ With chaining → "Something broke because X happened" ✅ 🔥 Small concept, but BIG impact in real projects! #Java #ExceptionHandling #Programming #Coding #Developers #Backend #SoftwareEngineering #LearningJourney
To view or add a comment, sign in
-
-
🚀 Anonymous Class vs Lambda Expression in Java – Simple Guide Understanding the difference between Anonymous Classes and Lambda Expressions is important for every Java developer. Here’s a quick breakdown 👇 🔹 1. Anonymous Class A class without a name Used for one-time implementation or method override Works with: ✔ Normal Class ✔ Abstract Class ✔ Interface 💡 Useful when: You need more control Multiple methods need to be implemented 🔹 2. Lambda Expression A short way to write code Used only with Functional Interface (one abstract method) 💡 Useful when: You want clean and concise code Only one method logic is needed 🔁 Key Differences ✔ Anonymous Class → More code, more control ✔ Lambda → Less code, simple logic 📌 When to use what? Interface (1 method) → ✅ Lambda Interface (multiple methods) → ✅ Anonymous Class Abstract Class → ✅ Anonymous Class Normal Class → ✅ Anonymous Class 🎯 Interview Tip “Lambda expressions can be used only with functional interfaces, whereas anonymous classes can be used with classes, abstract classes, and interfaces.” 💡 Mastering these concepts helps in writing clean, efficient, and professional Java code. #Java #Programming #JavaDeveloper #Coding #Learning #Tech
To view or add a comment, sign in
-
As I continue exploring Java, one concept that stood out to me is the Optional class. While learning, I realized how frequently null values can cause issues in programs, especially leading to NullPointerException. Optional, introduced in Java 8, provides a cleaner and more structured way to handle such scenarios. What I understood about Optional: Optional is a container object that may or may not contain a value. Instead of returning null, we can return an Optional to clearly indicate that a value might be absent. Why I find it useful: It reduces the need for multiple null checks and makes the code more readable and expressive. It also encourages better coding practices by forcing us to think about handling missing values. Key methods I explored: Creation: - Optional.empty() - Optional.of(value) - Optional.ofNullable(value) Checking: - isPresent() - isEmpty() Retrieving: - get() (should be used carefully) - orElse(defaultValue) - orElseGet(Supplier) - orElseThrow() Transformation: - map() - flatMap() - filter() Actions: - ifPresent() - ifPresentOrElse() Example I tried: Optional<String> name = Optional.ofNullable("Java"); String result = name .map(String::toUpperCase) .orElse("DEFAULT"); My takeaway: Optional is not just a class, it is a better way of thinking about handling null values. I am still exploring it, but it already feels like a powerful tool for writing safer and cleaner Java code. Looking forward to learning more and applying it in real-world projects. #Java #OptinalClass
To view or add a comment, sign in
-
💡 What are Constructors in Java? (Explained Simply) When I started learning Java, constructors confused me a lot… Here’s the simplest way to understand them 👇 👉 A constructor is a special method used to initialize objects. It gets called automatically when we create an object. 🧠 Example: If we create a class "Employee", a constructor helps us assign values like name, id, etc. at the time of object creation. 🔥 Types of Constructors: 1️⃣ Default Constructor - No parameters - Assigns default values 2️⃣ Parameterized Constructor - Takes inputs - Helps set custom values ⚠️ Important Points: ✔ Constructor name = class name ✔ No return type (not even void) ✔ Called automatically when object is created 💡 Why use constructors? Because they make object creation easy and clean. Still learning Java step by step 🚀 #Java #CodingJourney #LearnInPublic #100DaysOfCode
To view or add a comment, sign in
-
Discover how method overloading in Java enables flexible code by allowing multiple methods with the same name but different parameters.
To view or add a comment, sign in
-
Java Concept Check — Answer Explained 💡 Yesterday I posted a question: Which combination of Java keywords cannot be used together while declaring a class? Options were: A) public static B) final abstract C) public final D) abstract class ✅ Correct Answer: B) final abstract Why? In Java: 🔹 abstract class - Cannot be instantiated (no direct object creation) - Must be extended by another class Example: abstract class A { } 🔹 final class - Cannot be extended by any other class - Object creation is allowed Example: final class B { } The contradiction If we combine them: final abstract class A { } We create a conflict: - "abstract" → class must be inherited - "final" → class cannot be inherited Because these two rules contradict each other, Java does not allow this combination, resulting in a compile-time error. Thanks to everyone who participated in the poll 👇 Did you get the correct answer? #Java #BackendDevelopment #JavaDeveloper #Programming
To view or add a comment, sign in
-
🚀 Day 49 – Mastering ArrayList Methods in Java Today I focused on one of the most powerful parts of the Java Collections Framework – the ArrayList and its important methods. 📌 Key Learnings: 🔹 Dynamic data structure (resizable array) 🔹 Allows duplicates & maintains insertion order 🔹 Efficient data manipulation using built-in methods 💡 Methods I explored: ✔ add() – Insert elements ✔ add(index, value) – Insert at specific position ✔ addAll() – Merge collections ✔ remove() / removeAll() – Delete elements ✔ retainAll() – Keep common elements ✔ set() – Replace values ✔ get() – Access elements ✔ size() – Count elements ✔ contains() – Search elements ✔ subList() – Extract partial data ✔ clear() – Remove all data ✔ trimToSize() – Optimize memory 🔥 Key Insight: Understanding the difference between add() vs set() is crucial: add() → shifts elements set() → replaces elements 📊 These methods are not just theory — they are heavily used in real-world applications for managing and processing data efficiently. 💭 Takeaway: Mastering ArrayList methods improves problem-solving and builds a strong foundation in Java programming. #Java #ArrayList #CollectionsFramework #Programming #CodingJourney #JavaDeveloper #Learning #Day49
To view or add a comment, sign in
-
-
🚀 Why Runnable is Preferred Over Thread in Java? Many beginners start with extending the Thread class, but in real-world development, Runnable (or lambda) is the preferred approach. Let’s understand why 👇 🔹 Problem with Thread Class Java supports single inheritance. 👉 If you write: class A extends Thread ❌ You cannot extend any other class 🔹 Real-Time Scenario class A extends B 👉 Now you want threading also… ❌ You CANNOT do: class A extends B, Thread // Not possible 🔹 Solution: Use Runnable(Functional Interface)✅ class A extends B implements Runnable { public void run() { System.out.println("Running"); } } 👉 Now you can: ✔ Extend another class ✔ Use threading ✔ Follow clean design 🔹 Why Runnable is Better? ✔ Supports flexibility ✔ Follows good design (separates task & thread) ✔ Works with modern APIs (ExecutorService, ThreadPool) ✔ Supports lambda expressions 🎯 Key Takeaway 👉 “Since Java supports single inheritance, we use Runnable instead of extending Thread to achieve better flexibility and design.” #Java #Multithreading #JavaDeveloper #Coding #SoftwareEngineering #Learning
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development