🚀 Learning Core Java – Method Hiding & Variable Hiding Today I explored an interesting concept in Java — Method Hiding and Variable Hiding. When a class inherits properties and behavior from another class, we usually talk about method overriding. But things behave differently when static methods and variables are involved. 🔹 Method Hiding (Static Methods) In Java: ✔ Instance methods → can be overridden ✔ Static methods → cannot be overridden If a child class defines a static method with the same signature as the parent: 👉 It does NOT override the method 👉 Instead, it hides the parent method This is called Method Hiding. 🔎 Important: • The method that gets executed depends on the reference type, not the object type • This is resolved at compile-time (not runtime) 🔹 Variable Hiding When a child class declares a variable with the same name as in the parent class: 👉 The child variable hides the parent variable This applies to: ✔ Static variables ✔ Instance variables 🔎 How to Access Parent Members? We use the super keyword to access hidden members of the parent class: ✔ super.variable → Access parent variable ✔ super.method() → Access parent method (if needed) 💡 Key Insight 👉 Instance methods → Overriding (Runtime Polymorphism) 👉 Static methods → Method Hiding (Compile-time behavior) 👉 Variables → Always Hiding (No overriding concept) Understanding this difference helps in avoiding confusion and writing predictable and clean Java code. Excited to keep strengthening my Core Java fundamentals! 🚀 #CoreJava #MethodHiding #VariableHiding #JavaProgramming #ObjectOrientedProgramming #JavaDeveloper #ProgrammingFundamentals #LearningJourney
KARTHIC RAGUNATH S B’s Post
More Relevant Posts
-
🚀 Optimizing Java Switch Statements – From Basic to Modern Approach Today I explored different ways to implement an Alarm Program in Java using switch statements and gradually optimized the code through multiple versions. This exercise helped me understand how Java has evolved and how we can write cleaner, more readable, and optimized code. 🔹 Version 1 – Traditional Switch Statement The basic implementation uses multiple case statements with repeated logic for weekdays and weekends. While it works, it results in code duplication and reduced readability. 🔹 Version 2 – Multiple Labels in a Case Java allows grouping multiple values in a single case (e.g., "sunday","saturday"). This reduces repetition and makes the code shorter and easier to maintain. 🔹 Version 3 – Switch Expression with Arrow (->) Java introduced switch expressions with arrow syntax. This removes the need for break statements and makes the code cleaner and less error-prone. 🔹 Version 4 – Compact Arrow Syntax Further simplification using single-line arrow expressions improves code readability and conciseness. 🔹 Version 5 – Returning Values Directly from Switch Instead of declaring a variable and assigning values inside cases, the switch expression directly returns a value, making the code more functional and elegant. 🔹 Version 6 – Using yield in Switch Expressions The yield keyword allows returning values from traditional block-style switch expressions, providing more flexibility when writing complex logic. 📌 Key Learning: As we move from Version 1 to Version 6, the code becomes: More readable Less repetitive More modern with Java features Easier to maintain and scale These small improvements show how understanding language features can significantly improve the quality of code we write. 🙏 A big thank you to my mentor Anand Kumar Buddarapu for guiding me through these concepts and encouraging me to write cleaner and optimized Java code. #Java #JavaProgramming #CodingJourney #SoftwareDevelopment #LearnJava #SwitchStatement #Programming #DeveloperGrowth
To view or add a comment, sign in
-
💎 Understanding the Diamond Problem in Java (and how Java solves it!) Ever heard of the Diamond Problem in Object-Oriented Programming? 🤔 It happens in multiple inheritance when a class inherits from two classes that both have the same method. The Problem Structure: Class A → has a method show() Class B extends A Class C extends A Class D extends B and C Now the confusion is: Which show() method should Class D inherit? This creates ambiguity — famously called the Diamond Problem Why Java avoids it? Java does NOT support multiple inheritance with classes. So this problem is avoided at the root itself. But what about Interfaces? Java allows multiple inheritance using interfaces, but resolves ambiguity smartly. If two interfaces have the same default method, the implementing class must override it. Example: interface A { default void show() { System.out.println("A"); } } interface B { default void show() { System.out.println("B"); } } class C implements A, B { public void show() { A.super.show(); // or B.super.show(); } } Key Takeaways: No multiple inheritance with classes in Java Multiple inheritance allowed via interfaces Ambiguity is resolved using method overriding Real Insight: Java doesn’t just avoid problems — it enforces clarity. #Java #OOP #Programming #SoftwareDevelopment #CodingInterview #TechConcepts
To view or add a comment, sign in
-
DAY 33: CORE JAVA TAP Academy 🔁 Mastering Method Overriding in Java – Key Rules You Must Know! Method overriding is a core concept in Java that supports runtime polymorphism. But to use it correctly, you need to follow some important rules 👇 ✅ 1. Access Modifier Rule The access level of the overridden method cannot be more restrictive than the parent class method. ✔ Allowed: "protected → public" ❌ Not allowed: "public → private" ✅ 2. Return Type Rule The return type must be the same as in the parent class method. ✅ 3. Covariant Return Type Java allows a special case where the return type can be a subclass of the original return type. 👉 This is called a covariant return type and adds flexibility while maintaining compatibility. ✅ 4. Parameters Rule The method signature must remain exactly the same (same name and parameters). ⚠ Changing parameters = Method Overloading, not Overriding. 💡 Quick Tip: Always use "@Override" annotation — it helps catch mistakes at compile time! 📌 Understanding these rules is essential for writing clean, bug-free object-oriented code and cracking Java interviews. #Java #OOP #MethodOverriding #Programming #CodingInterview #SoftwareDevelopment
To view or add a comment, sign in
-
-
🚀 Understanding Method Overloading in Java 🔥 Let's break down the concept of method overloading in Java! Method overloading allows developers to define multiple methods with the same name but different parameters, making code more flexible and readable. This means you can have multiple methods with the same name, as long as the parameters differ in type or number. ⚡️ Why does method overloading matter for developers? It helps streamline code by promoting code reusability and enhancing readability. By using method overloading, developers can create cleaner code that is easier to maintain and understand. 👨💻 Here's a step-by-step breakdown: 1️⃣ Create multiple methods with the same name 2️⃣ Ensure the parameters are different in either type or number 3️⃣ The Java compiler determines which method to execute based on the arguments provided 📝 Full code example: ``` public class Calculate { public int sum(int a, int b) { return a + b; } public double sum(double a, double b) { return a + b; } } ``` 💡 Pro tip: Avoid overloading methods with the same number and type of parameters, as it can lead to ambiguity. ⚠️ Common mistake: Forgetting that the return type of the overloaded methods can be the same. ❓ How do you use method overloading in your Java projects? Do you have any favorite tricks? Share below! 💬 🌐 View my full portfolio and more dev resources at tharindunipun.lk #JavaProgramming #MethodOverloading #CodeFlexibility #LearnToCode #DeveloperTips #CleanCode #JavaDev #CodingCommunity #TechTalks
To view or add a comment, sign in
-
-
🚀 Learning Core Java – Understanding the final Keyword Today I explored an important concept in Java — the final keyword. The final keyword is used to restrict modification and helps make code more secure, predictable, and stable. It can be used with: ✔ Variables ✔ Methods ✔ Classes 🔹 1. Final Variable If a variable is declared as final: 👉 Its value cannot be changed once assigned It becomes a constant. Example conceptually: final int MAX = 100; This improves safety and prevents accidental modification. 🔹 2. Final Method If a method is declared as final: 👉 It cannot be overridden by the child class This is useful when we want to preserve the original behavior of a method. 🔹 3. Final Class If a class is declared as final: 👉 It cannot be inherited This is used when we want to stop extension of a class for security or design reasons. Example: String class is a famous final class in Java. 🔎 Why abstract and final Cannot Be Used Together These two keywords contradict each other: ✔ abstract → Must be overridden ✔ final → Cannot be overridden Because of this: ❌ abstract final is not allowed in Java 🔹 Difference Between final, finally, and finalize() final ✔ A keyword ✔ Used with variables, methods, and classes finally ✔ A block used with try or try-catch 👉 It executes whether exception occurs or not Mainly used for cleanup operations like closing files or database connections. finalize() ✔ A method of the Object class 👉 Called internally by the Garbage Collector before object destruction ⚠ Deprecated since JDK 9 due to unpredictable behavior and performance issues. 💡 Key Insight 👉 final = Restriction 👉 finally = Cleanup block 👉 finalize() = Garbage collection method Understanding these small differences avoids big confusion during interviews and real projects. Excited to keep strengthening my Core Java fundamentals! 🚀 #CoreJava #FinalKeyword #JavaDeveloper #ObjectOrientedProgramming #ProgrammingFundamentals #LearningJourney #SoftwareEngineering
To view or add a comment, sign in
-
-
📅🚀 Date Formats in Java Handling date and time is a crucial part of building real-world applications — from logging events to scheduling systems. While learning Java, I explored how powerful the java.time package is for managing dates efficiently and cleanly. 📌 Key Classes You Should Know: • LocalDate → Handles only date (year, month, day) • LocalTime → Handles time (hours, minutes, seconds) • LocalDateTime → Combines both date & time 📌 Formatting & Parsing Dates: Using DateTimeFormatter, we can easily convert dates into readable formats and vice versa. 🔹 Example: LocalDate date = LocalDate.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); String formattedDate = date.format(formatter); 📌 Popular Date Patterns: • dd-MM-yyyy → 31-03-2026 • yyyy-MM-dd → 2026-03-31 • dd/MM/yyyy → 31/03/2026 • MMM dd, yyyy → Mar 31, 2026 📌 Why It Matters: ✔ Ensures consistency across applications ✔ Improves readability for users ✔ Helps in internationalization (different regions use different formats) ✔ Essential for backend systems, APIs, and databases 💡 Small improvements like proper date formatting can make your applications look more professional and user-friendly. What date format do you usually use in your projects? 👇 Grateful to my mentor Anand Kumar Buddarapu for guiding me and helping me understand real-world concepts in Java. #Java #Programming #Coding #JavaDeveloper #TechLearning #SoftwareDevelopment #DeveloperJourney
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
-
🚀 Learning Core Java – Understanding toString() Method and Its Significance Today I explored one of the most commonly used methods from the Object class in Java — the toString() method. Since every class in Java implicitly extends the Object class, every object gets access to the toString() method by default. 🔹 What is toString()? The toString() method is used to return the string representation of an object. Whenever we print an object directly using: System.out.println(object); Java internally calls: object.toString(); 🔹 Default Behavior of toString() By default, the toString() method returns: 👉 ClassName@HexadecimalHashCode 🔹 Why Do We Override toString()? To make object output more readable and meaningful, we override the toString() method. Instead of memory-like output, we can display useful information such as: ✔ Name ✔ ID ✔ Age ✔ Product Details ✔ Employee Information This improves: ✔ Debugging ✔ Logging ✔ Readability ✔ User-friendly output 💡 Key Insight 👉 toString() converts an object into a meaningful string representation 👉 Default output is technical and less useful 👉 Overriding it improves clarity and maintainability A well-written toString() method makes Java code cleaner and easier to understand. Excited to keep strengthening my Core Java fundamentals! 🚀 #CoreJava #ToStringMethod #ObjectClass #JavaProgramming #OOP #JavaDeveloper #ProgrammingFundamentals #LearningJourney
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
-
🚀 Learning Core Java – Understanding Aggregation and Composition Today I explored an important OOP concept in Java — Aggregation and Composition. Both Aggregation and Composition are called Associative Relationships because they represent the “Has-A” relationship between classes. This means one class contains or uses objects of another class instead of inheriting from it. 🔹 What is Has-A Relationship? In this relationship: ✔ There is one Primary Class ✔ There can be one or more Secondary Classes The way secondary class objects participate inside the primary class defines the type of relationship. 🔹 Aggregation Aggregation means: 👉 The secondary class can exist independently, even without the primary class. This represents a weak association. Example: 📱 Mobile has a Charger Even if the mobile phone is removed, the charger can still exist independently. So this is Aggregation. 🔹 Composition Composition means: 👉 The secondary class cannot exist independently without the primary class. This represents a strong association. Example: 📱 Mobile has an Operating System Without the mobile phone, the operating system has no separate meaningful existence in that context. So this is Composition. 🔎 Simple Difference ✔ Aggregation → Independent existence possible ✔ Composition → Dependent existence only 💡 Key Insight Aggregation and Composition help us model real-world relationships more accurately and build better object-oriented designs. 👉 Both are Has-A relationships 👉 Aggregation = Weak association 👉 Composition = Strong association Understanding these concepts is essential for writing clean, scalable, and maintainable Java applications. Excited to keep strengthening my OOP fundamentals! 🚀 #CoreJava #Aggregation #Composition #ObjectOrientedProgramming #HasARelationship #JavaDeveloper #ProgrammingFundamentals #LearningJourney
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