Java Trick Question: Inheritance Without extends? A few days ago, I came across an interview question that made me pause: 👉 “Can you achieve inheritance in Java without using the extends keyword?” At first glance, it feels like a trick — because we’re so used to extends for classes and implements for interfaces. But here’s the twist 👇 💡 Yes, you can — through composition and interface inheritance! For example: interface Animal { void sound(); } class Dog implements Animal { public void sound() { System.out.println("Woof!"); } } Here, Dog inherits behavior from Animal — but there’s no extends in sight. That’s interface-based inheritance. And there’s more — You can also achieve reuse (a form of inheritance) using composition, by including an object of another class inside your class and delegating behavior to it. Example: class Engine { void start() { System.out.println("Engine started"); } } class Car { private Engine engine = new Engine(); void start() { engine.start(); } // Behavior reuse without 'extends' } 🔹 No extends. 🔹 Yet, functionality is “inherited.” 🔹 This is known as composition over inheritance — one of the key design principles in OOP. So next time someone asks, “Can you achieve inheritance without extends?” You can confidently say: “Yes — through interfaces and composition!” 💪 #Java #OOP #Inheritance #InterviewQuestion #Developers #LearningEveryday
Achieving Inheritance in Java Without Extends
More Relevant Posts
-
Polymorphism in Java is a key concept in object-oriented programming that allows one entity—such as a method, object, or operator—to take many forms and behave differently based on its context within the class hierarchy. What Is Polymorphism? The word "polymorphism" means "many forms .In Java, it lets you perform a single action in various ways depending on which object or class is involved, enabling reusable and flexible code. Types of Polymorphism in JavaCompile-Time Polymorphism (Static/Method Overloading): Multiple methods with the same name but different parameters within the same class. The method executed depends on the argument types and number at compile time .Runtime Polymorphism (Dynamic/Method Overriding): When a subclass provides its own version of a method defined in its superclass. The method that's called is determined at runtime, based on the object's actual class. Runtime Polymorphism: class Animal { public void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { @Override public void sound() { System.out.println("Dog barks"); } } public class Main { public static void main(String[] args) { Animal myAnimal = new Dog(); myAnimal.sound(); // Outputs "Dog barks" } } Compile time Polymorphism: class Calculator { public int add(int a, int b) { return a + b; } public double add(double a, double b) { return a + b; } } Calculator calc = new Calculator(); calc.add(5, 10); // Calls int version calc.add(5.5, 10.5); // Calls double version Why Is Polymorphism Useful? Promotes code reusability and cleaner code structure. Enables easy maintenance and flexibility, since new behaviors can be added with minimal changes to existing code #Polymorphism #OOP #CodeBetter
To view or add a comment, sign in
-
Java String getBytes() Explained: Your Ultimate Guide to Character Encoding Java String getBytes() Explained: Stop Letting Character Encoding Ruin Your Code Let's be real for a second. When you're starting with Java, String objects feel like magic. You can add them, split them, compare them... life is good. Then, you need to save that text to a file, send it over a network, or maybe hash it for a password. Suddenly, the universe throws a scary term at you: byte arrays. And right there, in the middle of the confusion, is the getBytes() method. You've probably seen it, maybe even used it with a shrug, hoping it would just work. Spoiler alert: sometimes it doesn't. You end up with garbled text, weird question marks (�), or characters that look like they're from a alien language. Ever seen "Café" instead of "Café"? Yep, that's the enemy we're fighting today. Don't worry, we've all been there. This guide is your deep dive into the String.getBytes() method. We're going to break it down, not just tell you what it does, but why it does it, and how you can use it li https://lnkd.in/gppmqqtG
To view or add a comment, sign in
-
🚀 Understanding Immutable vs Mutable Strings — Made Simple! Today, I was revising how Strings actually work in Java — and it hit me how interesting the difference between immutable and mutable strings really is! Here’s what I learned (in simple terms 👇): 🔹 Immutable Strings (String) Once created, they cannot be changed. Any modification (like s = s + "World") actually creates a new String in memory. Example: String s = "Hello"; s = s + " World"; // Creates a new object "Hello World" This is why Strings are safe, thread-friendly, and perfect for constants — but they can be slower if used in loops or heavy text operations. 🔹 Mutable Strings (StringBuilder / StringBuffer) These can be changed directly without creating new objects. Internally, they use a modifiable char array, so operations like append() just update the same memory. StringBuilder sb = new StringBuilder("Hello"); sb.append(" World"); // Changes the same object Great for performance and memory efficiency, especially in loops or dynamic text building. 🧠 Simple way to remember: Immutable = Ice cube 🧊 (can’t reshape it once frozen) Mutable = Water 💧 (you can move and reshape it anytime) Learning how strings are stored and managed internally really helps you write cleaner and faster Java code. Sometimes, understanding the why behind these small things makes a big difference. 🚀 💬 Curious to hear — did you also find this concept confusing when you first learned about it? #Java #Programming #Learning #String #SoftwareDevelopment #Coding #Developers #Tech
To view or add a comment, sign in
-
-
Master the Java String join() Method: A 2025 Guide with Examples & Best Practices Stop Fumbling with Strings: A No-BS Guide to Java's String.join() Let's be real. How many times have you written a clunky for-loop just to stick a bunch of strings together with a comma? You know, the classic dance: java List<String> list = Arrays.asList("Java", "Python", "JavaScript"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < list.size(); i++) { sb.append(list.get(i)); if (i < list.size() - 1) { sb.append(", "); } } System.out.println(sb.toString()); // Output: Java, Python, JavaScript What if I told you there's a cleaner, more elegant, and frankly, more awesome way to do this? Enter the String.join() method. It’s one of those "why didn't they add this sooner?" features that makes your code instantly more readable and professional. In this deep dive, we're not just going to glance at the syntax. We're going to tear it apart, see it in action with real-world stuff, and discuss when to use it and when to maybe use something else. Let's get to it https://lnkd.in/ddSTAa7T
To view or add a comment, sign in
-
Master the Java String join() Method: A 2025 Guide with Examples & Best Practices Stop Fumbling with Strings: A No-BS Guide to Java's String.join() Let's be real. How many times have you written a clunky for-loop just to stick a bunch of strings together with a comma? You know, the classic dance: java List<String> list = Arrays.asList("Java", "Python", "JavaScript"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < list.size(); i++) { sb.append(list.get(i)); if (i < list.size() - 1) { sb.append(", "); } } System.out.println(sb.toString()); // Output: Java, Python, JavaScript What if I told you there's a cleaner, more elegant, and frankly, more awesome way to do this? Enter the String.join() method. It’s one of those "why didn't they add this sooner?" features that makes your code instantly more readable and professional. In this deep dive, we're not just going to glance at the syntax. We're going to tear it apart, see it in action with real-world stuff, and discuss when to use it and when to maybe use something else. Let's get to it https://lnkd.in/ddSTAa7T
To view or add a comment, sign in
-
💡 Mastering Type Casting in Java: Upcasting vs. Downcasting 🎭 When working with class hierarchies (Parent-Child relationships), Type Casting is essential for controlling which methods an object reference can access. Let's use a common example: a parent class Employee and a child class Manager. 1. Upcasting (Safe & Automatic) What it is: Treating a child object as a parent object. Code Example: Employee obj = new Manager(); Safety: Always safe because a Manager is a specific kind of Employee. The compiler allows this automatically. Limitation: The obj reference can only call methods defined in the Employee class. Any methods unique to Manager are inaccessible. 2. Downcasting (Risky & Explicit) What it is: Treating a parent reference as a child reference. Code Example: Manager mgr = (Manager) obj; Safety: Risky, requiring an explicit cast (Manager). If the obj variable does not actually hold a Manager object at runtime, a ClassCastException will be thrown. Purpose: The only reason to downcast is to regain access to methods that are unique to the Manager class (e.g., mgr.calculateBonus()). 🔑 The Golden Rule of Casting Always remember this key principle: A reference variable's type determines what methods you can call (compile-time), but the object's actual type determines which method runs (run-time, thanks to Polymorphism). Upcasting is the standard, secure way to use polymorphism. Downcasting should be used sparingly and often preceded by an instanceof check to prevent runtime errors. Understanding these mechanics is key to writing robust and flexible OOP code! Thank you sir Anand Kumar Buddarapu,Saketh Kallepu,Uppugundla Sairam,Codegnan #Java #OOP #ProgrammingTips #TypeCasting #Polymorphism #SoftwareDevelopment
To view or add a comment, sign in
-
-
🔐 Mastering final in Java — 8 Key Questions Answered Understanding final in Java is essential for writing secure, optimized, and immutable code. Here's a quick breakdown of the most asked questions: 💡 1. Why can't we extend a final class? Because Java wants to lock its behavior — no subclassing allowed. But it can still implement interfaces! 🔁 2. Can a final method call an overridden method? Yes — it can call other methods, even overridden ones, as long as it’s not being overridden itself. 🧠 3. What if a final variable points to a mutable object? You can't reassign the reference, but you can still mutate the object. java final List<String> names = new ArrayList<>(); names.add("Alice"); // ✅ names = new ArrayList<>(); // ❌ 🔄 4. Can a local variable be final and still change? Yes — if it points to a mutable object, its internal state can change. 🧱 5. What happens if we try to extend a final class? Compile-time error — whether inside or outside the package. ⚙️ 6. Can a final method be static? Absolutely. It locks the method completely — no override, no polymorphism. 🧩 Can a final method exist in an abstract class? Yes. Abstract classes can have concrete final methods to enforce behavior. 🚦 How does final affect method dispatch? It disables dynamic dispatch, allowing faster execution and compiler optimizations. If a method is final, Java does not need to check for overrides, enabling faster dispatch and potential compiler optimization 🧊 Bonus: Designing an Immutable Class public final class Person { private final String name; private final int age; public Person(String name, int age) { this.name = name; this.age = age; } } 🔒 Final class + final fields = true immutability. #Java #FinalKeyword #Immutability #SoftwareDesign #LinkedInLearning
To view or add a comment, sign in
-
Polymorphism in Java (One Action, Many Meanings) The word “poly” means many and “morph” means forms or shapes. So, Polymorphism = One thing, many forms 🌀 🎯 Daily Life Example: 👉 The word “run” — A boy can run 🏃♂️ A fan can run 💨 A program can run 💻 Same word — but used in different meanings depending on the situation! That’s exactly what happens in Java Polymorphism. One function (method) can behave differently based on the object that’s using it. 💻 Simple Java Example: class Animal { void sound() { System.out.println("Animals make sound 🎵"); } } class Dog extends Animal { void sound() { System.out.println("Dog barks 🐶"); } } class Cat extends Animal { void sound() { System.out.println("Cat meows 🐱"); } } public class Main { public static void main(String[] args) { Animal a1 = new Dog(); Animal a2 = new Cat(); a1.sound(); // Dog barks 🐶 a2.sound(); // Cat meows 🐱 } } 🧠 In Simple Words: Same method, different results. The method changes its behavior based on the object calling it. It makes your code flexible and smart. 🏠 Real-Life Example: A remote control 🕹️ — the same button “power” works for TV, AC, or fan but performs different actions. A mobile camera 📱 — same “click” button, but works differently in photo, video, or portrait mode. That’s Polymorphism in real life — one action, many results! ✨ Takeaway: Polymorphism = Same action, different behavior 💪 It helps make your code clean, reusable, and powerful. #Java #OOP #Polymorphism #Programming #Learning #DailyLearning #CodingSimplified #Developers
To view or add a comment, sign in
-
Ever wondered why Java has a hybrid execution model involving both compilation & interpretation? Most languages are either fully compiled (like C/C++) or fully interpreted (like Python, JavaScript). This mixed runtime design is very instrumental to the "Write Once, Run Anywhere" philosophy of Java. When you want to execute a Java program, the javac compiler would compile it into a platform-independent bytecode. This is a low-level intermediate language consisting of single-line instructions. Each opcode (operation type) occupies exactly 1 byte (hence the name bytecode). This bytecode is then interpreted by JVM to run the program. Note, that the JVM is dependent on underlying platform, but it can take bytecode compiled from any platform and run it. This makes Java code portable across devices. Why not fully compile the source code? It tightly couples the output to a specific platform, and hence not something u can port anywhere. Although, if you want this, GraalVM can be used instead of traditional JVM. Why not fully interpret and run directly? It's too slow, and we would miss out on compiler optimizations our source code can benefit from. Modern JVMs also include a JIT compiler to optimize the JVM interpreter even more. JIT analyses the running bytecode and compiles repetitive instructions to machine code for better performance. Thus every Java program on JVM, starts off slow but becomes more performant over time as JIT optimizes the "hot-spots" of bytecode to machine code. JIT can perform specific optimizations depending on platform & run-time behaviour which a normal compiler cannot do.
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