Polymorphism in Java with real time example Concept: Polymorphism in Java Definition: Polymorphism means “many forms.” In Java, it allows one object to behave in multiple ways depending on the situation. In simple words: Polymorphism = One action, many implementations. It’s one of the core pillars of OOP — enabling flexibility, scalability, and code reusability. Why it matters ✅ Improves code flexibility and extensibility ✅ Supports runtime decision making ✅ Reduces duplication and enhances code maintenance ✅ Enables developers to write generic and reusable code Java supports two main types of Polymorphism: 1️⃣ Compile-time (Static) Method overloading — decided at compile time Same method name, different parameters 2️⃣ Runtime (Dynamic) Method overriding — decided at runtime Same method name, same parameters in subclass 1️⃣ Compile-Time Polymorphism (Method Overloading) When multiple methods have the same name but different parameters, Java decides which one to call at compile time. Example: class MathOperation { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } } Usage: MathOperation obj = new MathOperation(); System.out.println(obj.add(10, 20)); // calls int version System.out.println(obj.add(10.5, 20.3)); // calls double version 🧠 Real-Life Example: You can call a friend — using a mobile number, email, or social app — same action (call), but multiple ways to do it. 2️⃣ Runtime Polymorphism (Method Overriding) When a child class provides its own implementation of a method already defined in the parent class. Decision is made at runtime — based on the object type. Example: class Vehicle { void start() { System.out.println("Vehicle starts"); } } class Car extends Vehicle { @Override void start() { System.out.println("Car starts with key ignition"); } } public class Main { public static void main(String[] args) { Vehicle v = new Car(); // Parent reference, child object v.start(); // Output: Car starts with key ignition } } 🧠 Real-Life Example: When you press the “start” button, a petrol car, electric car, and bike all start differently, but the action name is the same — start(). Key Difference In compile-time polymorphism, the method to be executed is decided during compilation — this is called early binding (example: method overloading). In runtime polymorphism, the method to be executed is decided during program execution — this is called late binding (example: method overriding). Takeaway: Polymorphism helps you write flexible, reusable, and dynamic code by allowing the same action to behave differently in different scenarios. #Java #Polymorphism #OOPs #ProgrammingConcepts #SoftwareDevelopment #LearnJava #CodeBetter #ObjectOrientedProgramming #JavaLearning #MethodOverriding #MethodOverloading
Understanding Polymorphism in Java with Examples
More Relevant Posts
-
Abstraction in java with real time example Concept: Abstraction in Java Definition: Abstraction is the process of hiding internal implementation details and showing only essential features of an object. It focuses on what an object does, not how it does it. In simple words: Abstraction = Hiding Complexity + Showing Functionality 💡 Why it matters ✅ Reduces complexity — users don’t need to know internal logic. ✅ Increases code security — hides sensitive implementation. ✅ Makes code easier to maintain and update. ✅ Allows developers to focus on high-level design. How Abstraction Works in Java Java achieves abstraction in two main ways: Type Description 1️⃣ Abstract Class Can have both abstract (unimplemented) and non-abstract methods 2️⃣ Interface Fully abstract (methods without body), used to define a contract 1️⃣ Abstraction Using Abstract Class Example: abstract class Vehicle { abstract void start(); // abstract method (no body) void stop() { // concrete method System.out.println("Vehicle stopped."); } } class Car extends Vehicle { void start() { System.out.println("Car starts with key ignition."); } } Usage: public class Main { public static void main(String[] args) { Vehicle v = new Car(); // reference of abstract class v.start(); // Calls Car's implementation v.stop(); // Calls Vehicle's method } } Explanation: Here, the user doesn’t need to know how the car starts — just calls start(). The implementation details are hidden inside the Car class. 2️⃣ Abstraction Using Interface Example: interface Payment { void pay(double amount); } class CreditCardPayment implements Payment { public void pay(double amount) { System.out.println("Paid " + amount + " using Credit Card."); } } class UpiPayment implements Payment { public void pay(double amount) { System.out.println("Paid " + amount + " using UPI."); } } Usage: public class Main { public static void main(String[] args) { Payment p = new UpiPayment(); p.pay(500.0); // Output: Paid 500.0 using UPI. } } Explanation: You don’t need to know the internal logic of how payment works — you just use the pay() method. Real-Life Analogy: Think about driving a car 🚘 You only know how to accelerate, brake, or steer, but you don’t need to know how the engine, fuel system, or ECU works internally. That’s Abstraction — hiding the complex details and exposing only what’s necessary. 📌 Takeaway: Abstraction lets you focus on what an object does, not how it does it. It simplifies complex systems by hiding the implementation and showing only essential features. #Java #Abstraction #OOPs #LearnJava #ProgrammingConcepts #SoftwareDevelopment #JavaLearning #ObjectOrientedProgramming #Encapsulation #Polymorphism #Inheritance #CodeBetter
To view or add a comment, sign in
-
⚡ Java Multithreading — What? Why? How? Multithreading can turn your single-core code into a performance powerhouse 💪 Here are 10 key concepts explained in What–Why–How format 👇 --- 1️⃣ What is Multithreading? What: Running multiple threads in one program. Why: Boosts performance by using CPU cores efficiently. How: Extend Thread or implement Runnable, then call start(). 2️⃣ Process vs Thread What: Process = independent program; Thread = lightweight unit inside it. Why: Threads share memory, reducing overhead. How: Java runs multiple threads inside the same JVM process. 3️⃣ Ways to Create Threads What: Extend Thread or implement Runnable. Why: To define behavior in run() for parallel tasks. How: new Thread(() -> System.out.println("Runnable running")).start(); 4️⃣ start() vs run() What: start() starts a new thread, run() is a normal call. Why: start() ensures true parallelism. How: thread.start(); // new thread thread.run(); // same thread 5️⃣ What is Synchronization? What: Controls access to shared resources. Why: Prevents race conditions. How: Use synchronized keyword or Lock objects. 6️⃣ Synchronized Methods vs Blocks What: Lock full method or part of code. Why: Protect critical sections only. How: synchronized void method() {} synchronized(this) { ... } 7️⃣ Deadlock What: Threads wait on each other forever. Why: Locks acquired in conflicting order. How: Avoid nested locks, maintain lock order, or use tryLock(). 8️⃣ wait(), notify(), notifyAll() What: Thread coordination methods. Why: Let threads communicate safely. How: wait() pauses thread; notify() wakes one; notifyAll() wakes all — used inside synchronized blocks. 9️⃣ synchronized vs Lock Interface What: Both manage synchronization. Why: Lock is more flexible (tryLock, fairness, interrupts). How: Lock l = new ReentrantLock(); l.lock(); try { ... } finally { l.unlock(); } 🔟 Thread-safe Classes What: Handle concurrent access safely. Why: Simplifies multi-threaded code. How: Internal synchronization — Vector, Hashtable, ConcurrentHashMap. --- 💡 Mastering these makes you not just a coder, but a concurrency engineer. Next up: Advanced Multithreading — volatile, ExecutorService, Callable, AtomicInteger. #Java #Multithreading #Concurrency #Synchronization #WhatWhyHow
To view or add a comment, sign in
-
☕ Java Revision Day: Objects in Arrays, Strings & Method Overloading 🔹 Today’s revision focused on a mix of object handling, string concepts, and polymorphism basics in Java — all of which strengthen the foundation for building dynamic programs. 💻 🧩 1️⃣ Objects in Arrays In Java, arrays don’t just store primitive data — they can also hold objects. This allows us to manage multiple instances of a class together, making data handling more structured and powerful. For example, you can store multiple Student, Employee, or Product objects inside a single array. It’s a key concept when working with real-world applications that deal with collections of data. Objects inside arrays can be accessed and manipulated individually — helping us perform operations like sorting, searching, or displaying object details easily. 💬 2️⃣ Introduction to Strings Strings are among the most commonly used objects in Java. They represent sequences of characters — like names, messages, or input data. In Java, Strings are objects of the String class, not primitive types. They come with powerful built-in methods for manipulation — such as concatenation, comparison, length checking, and substring operations. 🔒 3️⃣ Immutable Strings One of the most interesting facts about Strings in Java is that they are immutable. Once a String object is created, its value cannot be changed. When we modify a String, a new object is created instead of altering the existing one. This immutability ensures security, thread-safety, and memory efficiency, especially in applications involving multiple threads or frequent string operations. ⚙️ 4️⃣ Method Overloading Method Overloading is a form of compile-time polymorphism. It allows multiple methods in the same class to share the same name — as long as their parameters differ (in type, number, or order). This feature improves code readability and reusability, enabling methods to handle different input types while maintaining consistent naming. For instance, you might have multiple versions of a display() or add() method, each designed to handle various data types or arguments. 💡 Key Takeaways ✅ Arrays can hold objects, allowing efficient object grouping and management. ✅ Strings in Java are objects, not primitives. ✅ Strings are immutable, ensuring safety and reliability. ✅ Method Overloading brings flexibility and clarity in method design. 🎯 Reflection Today’s revision helped me understand how Java blends data organization, memory management, and object-oriented design. Concepts like immutable Strings and method overloading showcase how Java prioritizes both security and flexibility. 🚀 #Java #Programming #Coding #LearningJourney #DailyLearning #RevisionDay #FullStackDevelopment #SoftwareEngineering #TAPAcademy #TechCommunity #JavaDeveloper #StringsInJava #MethodOverloading #OOPsConcepts #ImmutableString #ArraysInJava
To view or add a comment, sign in
-
-
☕ Java Revision Day: Java Program Execution Flow 🔄 Today’s revision helped me connect all the dots between JDK, JRE, and JVM — understanding how a Java program actually runs behind the scenes. 💻 Let’s explore this step-by-step 👇 🧩 Step 1️⃣: Writing the Code We start by writing a simple Java program: class Hello { public static void main(String[] args) { System.out.println("Hello, Java World!"); } } Here, the file name is Hello.java (the source code). ⚙️ Step 2️⃣: Compilation Phase (JDK’s Role) When we run the command: javac Hello.java 🧠 The Java Compiler (javac) checks for syntax errors and converts the source code into bytecode, which is platform-independent. ✅ Output: A new file called Hello.class is created. This file doesn’t contain readable text — it holds bytecode (intermediate instructions for JVM). 🚀 Step 3️⃣: Execution Phase (JRE & JVM’s Role) Now we execute: java Hello Here’s what happens internally 👇 1️⃣ Class Loader Subsystem Loads Hello.class into memory. 2️⃣ Bytecode Verifier Ensures the code follows Java’s security rules (no illegal access). 3️⃣ JVM Execution Engine Interpreter reads bytecode line-by-line. JIT Compiler (Just-In-Time) converts frequently used code into native machine code for better performance. 4️⃣ Output Produced: Hello, Java World! 🧠 Step 4️⃣: Memory Management While executing, JVM allocates memory in different areas: Heap: Stores objects and instance variables. Stack: Holds method calls and local variables. PC Register & Method Area: Keep track of current instruction and class-level details. Garbage Collector: Automatically removes unused objects to free memory. 💡 Summary of the Flow: Source Code (.java) ↓ [javac compiler] Bytecode (.class) ↓ [JVM inside JRE] Machine Code → Output So, the process is: Write → Compile → Run → Execute → Output ✅ 🌍 Key Concept: Java follows the principle of WORA – Write Once, Run Anywhere. The .class bytecode can run on any system that has a JVM, whether it’s Windows, Linux, or macOS. 🎯 Reflection: Understanding this execution flow gave me a clear picture of how Java code transforms from simple text to a working program. It’s fascinating how the JDK, JRE, and JVM work together like gears in a machine to make Java reliable, secure, and portable! ⚙️ #Java #Programming #Coding #FullStackDevelopment #JVM #JRE #JDK #LearningJourney #SoftwareEngineering #DailyLearning #RevisionDay #TAPAcademy #TechCommunity #JavaExecution #CareerGrowth #WriteOnceRunAnywhere #TapAcademy
To view or add a comment, sign in
-
-
Java 2025: Smart, Stable, and Still the Future 💡Perfect 👩💻 ☕ Day 5: Tokens in Java In Java, tokens are the smallest building blocks of a program — like words in a sentence. When you write any Java code, the compiler breaks it into tokens to understand what each part means. There are 6 main types of tokens in Java 👇 🔑 1️⃣ Keywords Definition: Keywords are predefined, reserved words that Java uses for specific purposes. They tell the compiler how to interpret parts of the code. Key Points: 1. Keywords cannot be used as identifiers (like variable or class names). 2. All keywords are written in lowercase (e.g., public, class, if, return). 💡 Example: public class Example { int num = 10; } Here, public, class, and int are keywords. 🏷️ 2️⃣ Identifiers Definition: Identifiers are names given to variables, methods, classes, or objects — created by the programmer. Key Points: 1. They must start with a letter, underscore _, or dollar sign $. 2. Java is case-sensitive, so Name and name are different identifiers. 💡 Example: age, StudentName, calculateTotal() 🔢 3️⃣ Literals Definition: Literals represent fixed values that don’t change during program execution. Key Points: 1. They define constant values like numbers, text, or booleans. 2. Java supports different literal types — integer, float, string, char, and boolean. 💡 Example: int a = 10; String name = "Sneha"; boolean isJavaFun = true; ➕ 4️⃣ Operators Definition: Operators are symbols that perform actions on variables and values — like calculations or comparisons. Key Points: 1. They help in arithmetic, logical, and relational operations. 2. Operators simplify expressions and control decision-making in programs. 💡 Example: int sum = a + b; if (a > b) { ... } 🧱 5️⃣ Separators Definition: Separators are special symbols that separate and structure code elements in Java. Key Points: 1. They organize code blocks, statements, and method calls. 2. Common separators include (), {}, [], ;, and ,. 💡 Example: int arr[] = {1, 2, 3}; System.out.println(arr[0]); 💬 6️⃣ Comments Definition: Comments are non-executable text in a program used to describe, explain, or document the code. Key Points: 1. Comments improve code readability and maintenance. 2. They come in three types — single-line, multi-line, and documentation. 💡 Example: // This is a single-line comment /* This is a multi-line comment */ /** Documentation comment */ 🧠 In Summary Token Type Purpose Example Keyword Predefined reserved word public, class Identifier User-defined name name, add() Literal Constant value 10, "Hello" Operator Performs operation +, == Separator Structures code (), {} Comment Adds explanation // note #Day5OfJava #JavaLearning #JavaTokens #LearnJava #CodeDaily #JavaBasics #ProgrammersJourney #100DaysOfCode #JavaConcepts #CodingWithSneha
To view or add a comment, sign in
-
-
🚗 Tricky Java Bug — “When Ola’s Cache Broke Serialization: The serialVersionUID Mystery 🧩” 🎬 The Scene At Ola, a backend dev cached user data using Java serialization. Everything ran perfectly in staging. But the moment they deployed a new version… 💥 java.io.InvalidClassException: com.ola.user.UserInfo; local class incompatible: stream classdesc serialVersionUID = 124578, local class serialVersionUID = 987654 Suddenly, users vanished from cache faster than an Ola cab during rain 😅 💣 The Root Cause When Java serializes an object, it stores a unique identifier — serialVersionUID. If you don’t explicitly declare it, JVM generates one automatically based on class structure (fields, methods, etc.). So when someone adds or removes a field later, boom — the calculated ID changes, and deserialization fails because the stored bytes no longer match the “current version” of the class. ⚙️ The Problem Code public class UserInfo implements Serializable { private String name; private int age; private String city; } Then one fine day… someone adds a new field: private String gender; 💣 Old cache data can’t deserialize anymore. ✅ The Fix Always define a fixed serialVersionUID to maintain compatibility: public class UserInfo implements Serializable { private static final long serialVersionUID = 1L; private String name; private int age; private String city; private String gender; // newly added } 🧩 Quick Debugging Tips 🔍 Check the exception message — it always mentions both stream and local IDs. 🧠 Use serialver tool to generate UID for older class versions. 🚫 Don’t rely on JVM-generated IDs if your class might evolve over time. 💾 When backward compatibility isn’t needed — clear the cache before redeploy. 🔄 Consider using JSON-based cache (like Redis with Jackson) for human-readable, version-tolerant data. ✅ Quick Checklist ☑️ Always declare serialVersionUID manually. ☑️ Avoid unnecessary structural changes in serializable classes. ☑️ For distributed cache, prefer JSON serialization over Java native. ☑️ Be aware that adding/removing fields changes serialization compatibility. 💬 Real Talk At Ola, one dev said: > “My cache invalidated itself before I could even write the logic for it!” 😅 Lesson: In Java, serialVersionUID isn’t just a number — it’s your backward compatibility insurance policy. #Java #Serialization #Ola #TrickyBugs #Cache #BackendDevelopment #SpringBoot #Debugging #Developers #TechHumor #Concurrency #Microservices #JavaInterview #SoftwareEngineering
To view or add a comment, sign in
-
👨🏻💻🎒 Java Runtime Architecture: From Source to Execution 🏁 What actually happens when you run a Java program? 🤔💭 Here's the end-to-end path - short, accurate, and to the point. * You write java, javac compiles to platform-independent .class bytecode designed for a JVM, not directly for your CPU/OS. * Starting the JVM, when you command-in "java -jar app.jar" the OS launches a native process (java.exe on Windows). That process loads the JVM as native code (jvm.dll on Windows) and builds a runtime in the same process: heap, stacks, class metadata (Metaspace), threads. Note: The JVM isn't a separate OS process—it lives inside the Java process and manages its own memory and threads using OS allocations. * A JAR is a ZIP. The JVM (via ClassLoaders): * Reads META-INF/MANIFEST.MF for Main-Class (this can also be used to find entry-points) * Streams class bytes/resources from the JAR (it doesn't need to extract to disk) * Defines classes in memory. To the OS it's just file I/O, only the JVM understands the JAR's structure. * Hot code runs faster via tiered compilation: * Interpreter runs bytecode first * JIT compiles hot methods to native machine code in RAM * Result: portability with near-native speed. (Some distributions also support AOT, but JIT is the default.) * Java threads are native OS threads (1:1 mapping since Java 5). * File/network I/O, timers, memory reservation, etc., use the JVM's own native code calling OS APIs. * JNI is the standard bridge for your Java code to call native libraries when needed (not a requirement for ordinary I/O). What You'll See in Task Manager/Activity Monitor? * Typically a single java/java.exe process containing: * The loaded JVM library * Multiple native threads (GC, JIT, app) * Memory regions: heap, Metaspace, thread stacks * From the OS view, it's a normal native process using CPU/RAM. LONG STORY SHORT: * java → bytecode → JVM executes it * JVM runs inside a native process; no extra OS VM process * Tiered JIT compiles hot paths to native code at runtime * Java is "cross-platform" because the same bytecode runs on any compatible JVM #Java #JVM #SoftwareEngineering
To view or add a comment, sign in
-
-
If Polymorphism in Java ever made you scratch your head — this 3-minute breakdown will finally make it click 👇 🔹 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗣𝗼𝗹𝘆𝗺𝗼𝗿𝗽𝗵𝗶𝘀𝗺? “Polymorphism” literally means many forms. In Java, it lets the same method or object behave differently based on the object that’s calling it. 𝑬𝒙𝒂𝒎𝒑𝒍𝒆: A person can be a 𝒔𝒕𝒖𝒅𝒆𝒏𝒕 in college, an 𝒆𝒎𝒑𝒍𝒐𝒚𝒆𝒆 at work, or a 𝒔𝒐𝒏 at home — same person, different behaviors. 🔹 𝐓𝐲𝐩𝐞𝐬 𝐨𝐟 𝐏𝐨𝐥𝐲𝐦𝐨𝐫𝐩𝐡𝐢𝐬𝐦 𝐢𝐧 𝐉𝐚𝐯𝐚: 1️⃣ 𝐂𝐨𝐦𝐩𝐢𝐥𝐞-𝐭𝐢𝐦𝐞 𝐏𝐨𝐥𝐲𝐦𝐨𝐫𝐩𝐡𝐢𝐬𝐦 → Achieved using method overloading (same method name, different parameters). 2️⃣ 𝐑𝐮𝐧𝐭𝐢𝐦𝐞 𝐏𝐨𝐥𝐲𝐦𝐨𝐫𝐩𝐡𝐢𝐬𝐦 → Achieved using method overriding (subclass provides its own version of a superclass method). 🔹 𝐂𝐨𝐦𝐩𝐢𝐥𝐞-𝐭𝐢𝐦𝐞 𝐯𝐬 𝐑𝐮𝐧𝐭𝐢𝐦𝐞: 🧩𝐎𝐯𝐞𝐫𝐥𝐨𝐚𝐝𝐢𝐧𝐠 Happens within the same class and is decided by the compiler. It makes your code cleaner, more readable, and easier to maintain. ⚡𝐎𝐯𝐞𝐫𝐫𝐢𝐝𝐢𝐧𝐠 Happens between a superclass and its subclass and is decided at runtime based on the actual object. It adds flexibility and allows behavior customization. 🔹 𝐎𝐯𝐞𝐫𝐥𝐨𝐚𝐝𝐢𝐧𝐠 𝐯𝐬 𝐎𝐯𝐞𝐫𝐫𝐢𝐝𝐢𝐧𝐠 (𝐈𝐧 𝐬𝐢𝐦𝐩𝐥𝐞 𝐰𝐨𝐫𝐝𝐬). 𝐎𝐯𝐞𝐫𝐥𝐨𝐚𝐝𝐢𝐧𝐠 — Same method name, different inputs → compile-time decision. Think of it like having multiple doors with the same name tag but different sizes — the compiler decides which one fits best. 𝐎𝐯𝐞𝐫𝐫𝐢𝐝𝐢𝐧𝐠 — Same method signature, different behavior → runtime decision. It’s like the child replacing the parent’s door with a better one but keeping the same label — upgraded, yet familiar. ⚡ 𝐑𝐚𝐩𝐢𝐝-𝐟𝐢𝐫𝐞 𝐉𝐚𝐯𝐚 𝐐&𝐀 ⚡ 💬 Can we overload a method by changing only return type? → ❌ No, parameter list must differ. 💬 Can static methods be overloaded? → ✅ Yes. 💬 Can main() be overloaded? → ✅ Yes, but JVM calls only the standard one. 💬 Same number of parameters but different types? → ⚠ Compiler chooses the closest match or throws ambiguity error. 💬 Constructor overloading? → Multiple constructors with different parameters to create flexibility in object creation. 💬 Rules for overriding? → Same name, parameters, and return type; can’t reduce access; can’t override static/final methods. 💬 Can static methods be overridden? → ❌ No, they’re class-level (can only be hidden). 💬 Role of super keyword? → Used to call parent’s overridden method. 💬 Parent reference → Child object? → ✅ Allowed! Enables runtime polymorphism. 💬 Covariant return type? → Overridden method can return a subclass type for better type safety. #Java #OOPsConcepts #Polymorphism #BackendDevelopment #ProgrammingTips #JavaInterview #CodeWithMe #WithSir Suresh Bishnoi
To view or add a comment, sign in
-
-
I've worked with this library a lot and can say it's really helps with more or less simple object mapping, but if you have rather complicated relations between your classes it takes some time to build correct MapStruct infrastructure. I'd recomment everybody to dive deeper into the documentation and make your life easier. 😎 👍
💡 MapStruct in the project. 👉 MapStruct is a code—generation library for automatic mapping between Java objects. 👉 It works at the compilation stage, generates clean code without reflection, many times faster than ModelMapper and Dozer. 1️⃣ Adding dependencies: <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct</artifactId> </dependency> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> </dependency> OR implementation("org.mapstruct:mapstruct") implementation("org.mapstruct:mapstruct-processor") ⚠️ You need to add two dependencies: the mapstruct library itself and the mapstruct processor. The processor is responsible for code generation during compilation. 2️⃣ Create a Mapper interface: You are creating a regular Java interface with the @Mapper annotation (ComponentModel = "spring"). The ComponentModel parameter specifies that MapStruct should generate a Spring bean that can be injected through the constructor. In the interface, declare converter methods: for example, UserDTO toDto(User user) or List<UserDTO> toDtoList(List<User> users). MapStruct will figure out which fields to map into if the names match. 3️⃣ Set up custom mapping. When the field names are different or additional logic is needed, use the @Mapping annotation: ▪️ source/target — for renaming fields: @Mapping(target = "fullName", source = "firstName") expression — for Java expressions: you can write simple logic directly in the annotation. ▪️ ignore — to ignore the field: @Mapping(target = "password", ignore = true) DateFormat — for formatting dates: automatic conversion of LocalDateTime to String. ▪️ qualifiedByName — for calling custom converter methods. 4️⃣ Working with nested objects: MapStruct can automatically map nested structures. If you have an Address field in the User, and the UserDTO has an AddressDto, create a separate AddressMapper and specify it in the uses = parameter. {AddressMapper.class }. MapStruct will find the necessary mapper itself and apply it to the nested objects. This works recursively for any nesting depth. 5️⃣ Updating existing facilities: It is often necessary not to create a new object, but to update an existing one. To do this, use the @MappingTarget annotation on the second parameter of the method. MapStruct will generate code that will update only the required fields. Add @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE) — then null values from the DTO will not overwrite existing data in the Entity. ⁉️ What's going on under the hood? MapStruct analyzes your interface at compile time, examining the types of fields, their names, and annotations. Then it generates simple Java code with direct value assignments— no magic, reflection, or proxies. 📒 Documentation: https://lnkd.in/dMdKbmSb #programmingtips #softwaredevelopment #mapper
To view or add a comment, sign in
-
-
Java25 : main() , Compact Source, IO In Java 25 : The language significantly simplifies writing a main method by removing much of the traditional boilerplate. The new "Compact Source Files and Instance Main Methods" feature (JEP 512) allows you to write simple programs without a class wrapper, a public or static modifier, or the String[] args parameter. Writing main methods in Java 25 - 1.Traditional main method The classic, fully-featured main method remains the standard for most applications and is fully backward-compatible. // MyProgram.java public class MyProgram { public static void main(String[] args) { System.out.println("Hello, " + args[0] + "!"); } } 2. Simplified main method within a class For smaller programs, you can now write a less verbose main method inside a class, omitting the public, static, and String[] args parts. The JVM will look for this simplified version if it doesn't find the traditional one. java // HelloWorld.java class HelloWorld { void main() { System.out.println("Hello, World!"); } } 3. "Compact source file" with instance main For the most minimal entry point, you can place the simplified main method directly in a file without an enclosing class. The compiler automatically wraps the code in an implicit, unnamed class. // Minimal.java void main() { System.out.println("Hello from a compact source file!"); } 4. Using the java.lang.IO helper class To further reduce boilerplate for console I/O, Java 25 introduces a java.lang.IO helper class, making it easier to read and write from the console. java // IOExample.java import static java.lang.IO.*; void main() { var name = readln("What's your name? "); println("Hello, " + name + "!"); } Article: Java's main method gets a beginner-friendly reboot In its latest long-term support (LTS) version, Java 25, the platform has made a significant update to how developers, particularly beginners, can write the entry point to their programs. By finalizing JEP 512, which introduces "Compact Source Files and Instance Main Methods," Java has shed some of its long-standing "boilerplate" to become more accessible and intuitive. The feature, which was refined over several preview releases (including Java 21–24), provides a smoother on-ramp for new programmers by removing the need to understand complex, enterprise-level concepts like public, static, and the String[] args parameter from day one.
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
It's mainly important when we learn to stick with rules but implementation flow goes with work but rules important