Another way abstraction is implemented in Java is through interfaces. Interfaces define a set of methods that a class must implement, but they do not provide the actual implementation. Things that became clear : • an interface represents complete abstraction • methods declared inside an interface are implicitly public and abstract • a class uses the implements keyword to follow the rules defined by an interface • the implementing class must provide the body for all the methods • interfaces help create loose coupling between components A simple example shows the idea: interface ICalculator { void add(int a, int b); void sub(int a, int b); } class CalculatorImpl implements ICalculator { public void add(int a, int b) { System.out.println(a + b); } public void sub(int a, int b) { System.out.println(a - b); } } In this structure the interface defines what operations should exist, while the implementing class decides how those operations work. This approach makes it easier to design flexible and maintainable systems. #java #oop #programming #learning #dsajourney
Lakhyadeep Sen’s Post
More Relevant Posts
-
Q. Can an Interface Extend a Class in Java? This is a common confusion among developers and even I revisited this concept deeply today. - The answer is NO, an interface cannot extend a class. - It can only extend another interface. But there is something interesting: - Even though an interface doesn’t extend Object, all public methods of the Object class are implicitly available inside every interface. Methods like: • toString() • hashCode() • equals() These are treated as abstractly redeclared in every interface. ⚡ Why does Java do this? - To support upcasting and polymorphism, ensuring that any object referenced via an interface can still access these fundamental methods. ❗ Important Rule: While you can declare these methods in an interface, you cannot provide default implementations for them. interface Alpha { default String toString() { // ❌ Compile time error return "Hello"; } } Reason? Because these methods already have implementations in the Object class. Since every class implicitly extends Object, allowing default implementations of these methods in interfaces would create ambiguity during method resolution. Therefore, Java does not allow interfaces to provide default implementations for Object methods. 📌 Interfaces don’t extend Object, but its public methods are implicitly available. However, default implementations for them are not allowed. #Java #OOP #InterviewPreparation #Programming #Developers #Learning #SoftwareEngineering
To view or add a comment, sign in
-
The Diamond Problem in Java occurs in languages that allow multiple inheritance, where a class inherits from two classes that share a common superclass. This situation leads to ambiguity when both parent classes define the same method, raising the question of which method should be used. Java circumvents this issue by not supporting multiple inheritance with classes. However, a similar problem can arise with interfaces and default methods. Consider the following example: interface A { default void show() { System.out.println("A"); } } interface B { default void show() { System.out.println("B"); } } class Test implements A, B { public static void main(String[] args) { Test t = new Test(); t.show(); // This results in a compilation error } } In this case, since both interfaces provide the same method, Java requires the class to override it explicitly. Here’s how to resolve it with specific interface calls: class Test implements A, B { public void show() { A.super.show(); // Calls method from interface A B.super.show(); // Calls method from interface B } } This approach allows for explicit selection or combination of behavior from both interfaces. #Java #OOP #InterviewQuestions #BackendDevelopment #Programming
To view or add a comment, sign in
-
-
Interfaces in Java can also extend other interfaces. This allows one interface to build on top of another and combine multiple behaviours. Things that became clear : • an interface can extend one or more interfaces • the new interface inherits all the method declarations from the parent interfaces • any class implementing the child interface must provide implementations for all inherited methods • this helps organize related behaviours into structured layers • it also supports building more complex systems while keeping interfaces modular A simple example helps illustrate this idea : interface ICalculator { void add(int a, int b); void sub(int a, int b); } interface IAdvancedCalculator extends ICalculator { void mul(int a, int b); void div(int a, int b); } class CalculatorImpl implements IAdvancedCalculator { public void add(int a, int b) { System.out.println(a + b); } public void sub(int a, int b) { System.out.println(a - b); } public void mul(int a, int b) { System.out.println(a * b); } public void div(int a, int b) { System.out.println(a / b); } } Through this structure, interfaces can be combined and expanded while still maintaining clear rules for the implementing classes. #java #oop #programming #learning #dsajourney
To view or add a comment, sign in
-
🚀 Java Series – Day 10 📌 Abstraction in Java 🔹 What is it? Abstraction is an OOP concept that focuses on hiding implementation details and showing only essential functionality. In Java, abstraction can be achieved using: • Abstract Classes • Interfaces The idea is that the user only interacts with what the object does, not how it does it. 🔹 Why do we use it? Abstraction helps reduce complexity and improves code maintainability. For example: When you drive a car, you only use the steering, accelerator, and brake. You don’t need to understand the internal engine mechanism to drive it. Similarly in software, we expose only necessary features and hide internal logic. 🔹 Example: abstract class Animal { // Abstract method (no implementation) abstract void sound(); } class Dog extends Animal { // Implementation of abstract method void sound() { System.out.println("Dog barks"); } } public class Main { public static void main(String[] args) { Animal a = new Dog(); a.sound(); } } 💡 Key Takeaway: Abstraction hides internal complexity and exposes only the essential behavior to the user. What do you think about this? 👇 #Java #OOP #Abstraction #JavaDeveloper #Programming #BackendDevelopment
To view or add a comment, sign in
-
🚀 Why does Java allow only ONE public class per file? Java enforces a strict rule: 👉 A source file can contain only one public class. 🔍 Reason 1: File–Class Identity A public class is accessible outside its package, so it must have a clear identity. The compiler requires the file name to match the public class name. Example: public class Student → file must be named Student.java 🔍 Reason 2: Avoiding Ambiguity If multiple public classes were allowed in one file, the compiler would be confused about which one should be the entry point. To prevent this ambiguity, Java restricts it to a single public class. 🔍 Reason 3: Organized Project Structure This rule forces developers to keep each public class in its own file. Result: cleaner project organization, easier debugging, and better maintainability. ⚠️ What happens if you try multiple public classes? The compiler throws an error: “The public type X must be defined in its own file.” In short, Java simply doesn’t allow it.
To view or add a comment, sign in
-
-
Deep Dive into Core Java Concepts 🚀 Today, I explored some important Java concepts including toString(), static members, and method behavior in inheritance. 🔹 The toString() method (from Object class) is used to represent an object in a readable format. By default, it returns "ClassName@hashcode", but by overriding it, we can display meaningful information. 🔹 Understanding static in Java: ✔️ Static variables and methods are inherited ❌ Static methods cannot be overridden ✔️ Static methods can be hidden (method hiding) 🔹 What is Method Hiding? If a subclass defines a static method with the same name and parameters as the parent class, it is called method hiding, not overriding. 🔹 Key Difference: ➡️ Overriding → applies to instance methods (runtime polymorphism) ➡️ Method Hiding → applies to static methods (compile-time behavior) 🔹 Also revised execution flow: ➡️ Static blocks (Parent → Child) ➡️ Instance blocks (Parent → Child) ➡️ Constructors (Parent → Child) This learning helped me clearly understand how Java handles inheritance, memory, and method behavior internally. Continuing to strengthen my Core Java fundamentals 💻🔥 #Java #OOP #CoreJava #Programming #LearningJourney #Coding
To view or add a comment, sign in
-
-
I recently explored a subtle but important concept in Java constructor execution order. Many developers assume constructors simply initialize values, but the actual lifecycle is more complex. In this article, I explain: • The real order of object creation • Why overridden methods can behave unexpectedly • A common bug caused by partial initialization This concept is especially useful for interviews and writing safer object-oriented code. Medium Link: https://lnkd.in/gtRhpdfP #Java #OOP #SoftwareDevelopment #Programming
To view or add a comment, sign in
-
🚀 Before Learning Spring Boot, Understand Java Annotations Annotations in Java are used to provide metadata about the code, such as information about classes, methods, or variables. They do not directly change the program logic but help the compiler and frameworks understand how the code should be processed. Java also provides meta-annotations, which define how other annotations behave. Two important ones are: • @Target – Specifies where an annotation can be applied (class, method, field, parameter, etc.) • @Retention – Defines how long the annotation is available (source, class, or runtime) Annotations can also be understood in different ways: ✔ Compile-time annotations – Example: @Override, checked by the compiler during compilation. ✔ Runtime annotations – Example: @Deprecated, which can also be accessed at runtime using reflection. ✔ Target-based annotations – Example: @FunctionalInterface, which is applied at the interface level to ensure the interface has only one abstract method. Since Spring Boot is heavily annotation-driven, understanding Java annotations makes it easier to grasp concepts like dependency injection, configuration, and component scanning. Building strong fundamentals always makes learning frameworks much smoother. What was the first Java annotation you learned? 👇 #Java #SpringBoot #BackendDevelopment #Programming #LearningInPublic
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
-
⚡ Few powerful Java methods every developer should know Some Java methods look small… but they unlock powerful behavior under the hood. Here are a few that are worth understanding 👇 🔹 Class.forName() Loads a class dynamically at runtime 👉 Commonly used when the class name is not known at compile time (e.g., drivers, plugins) 🔹 Thread.yield() Hints the scheduler to pause the current thread 👉 Gives other threads a chance to execute (not guaranteed, just a suggestion) 🔹 String.intern() Moves a String to the String Pool (if not already present) 👉 Helps save memory by reusing identical string values 🔹 map.entrySet() Returns a set of key-value pairs from a Map 👉 Most efficient way to iterate both key and value together 🔹 Object.wait() Makes a thread wait until another thread notifies it 👉 Used for inter-thread communication (must be inside synchronized block) 🔹 Thread.join() Pauses current thread until another thread finishes 👉 Useful when execution order matters 🔹 stream().flatMap() Flattens nested data structures into a single stream 👉 Perfect for transforming lists of lists into a single list 💡 Why these matter? These methods touch core areas of Java: • Concurrency • Memory optimization • Collections • Functional programming Understanding them helps you write cleaner, more efficient code. 📌 Which one do you use most often? #Java #Programming #SoftwareDevelopment #Coding #BackendDevelopment #Tech
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