🚀 Day 32 – Core Java | Static Concepts & Introduction to Inheritance Today’s session connected two important concepts in Java: Static members and the second pillar of OOP – Inheritance. 🔑 Key Concepts Learned ✔ Static Variable Belongs to the class, not the object Only one copy exists in memory Used when a value is common for all objects Example: Bank interest rate or mathematical constant π ➡ Advantage: Efficient memory utilization ✔ Static Block Static blocks execute during class loading, even before the main() method. Two major uses: • Initialize static variables • Execute code before the program enters main() Execution order: Static Variables → Static Block → main() Method Multiple static blocks are allowed, and they execute in the order written in the program. ✔ Static Method Static methods can be accessed without creating an object. Example scenario: Converting Miles → Kilometers does not depend on any object. So the method can be declared as static. Called using: ClassName.methodName() Example: Car.milesToKilometer(380); ➡ Advantage: No object creation → Better memory usage ✔ Static vs Instance Access Rule Important concept from Java execution: • Static members can access only static data directly • Instance members can access both static and instance data Reason: Instance variables get memory only when an object is created, but static members execute during class loading. So static code cannot access something that doesn't yet exist in memory. 🧩 Introduction to Inheritance (2nd Pillar of OOP) Inheritance allows one class to acquire properties and behaviors of another class. Definition: Inheritance is the process where one class acquires the properties and behaviors of another class. Example: class Hacker extends BankAccount Here: • BankAccount → Parent / Superclass • Hacker → Child / Subclass ✔ Advantages of Inheritance • Code Reusability • Reduced development time • Less effort in building similar applications Real-world example: Many games reuse mechanics from earlier games, modifying only certain features instead of rebuilding everything. ✔ Important Rule Private members do NOT participate in inheritance Reason: Private data is protected by Encapsulation, and inheritance cannot violate that protection. ✔ First Type of Inheritance Single Inheritance Parent Class → Child Class Example: BankAccount → Hacker 💡 Biggest Takeaway Understanding static execution, memory behavior, and inheritance helps developers write code that is: Efficient Reusable Scalable These concepts form the foundation for advanced Java topics like polymorphism and abstraction. #Day32 #CoreJava #JavaOOP #StaticKeyword #Inheritance #JavaProgramming #DeveloperJourney #LearningJava
Java Day 32: Static Concepts & Inheritance
More Relevant Posts
-
📘 Inner Classes in Java — Complete & Clear Guide An Inner Class is a class defined inside another class. It is mainly used for logical grouping, encapsulation, and better code organization. --- 🔹 Types of Inner Classes 1. Member Inner Class • Defined inside a class (outside methods) • Can access all members of the outer class (including private) • Requires outer class object to instantiate 2. Static Nested Class • Declared with "static" keyword • Does not need outer class instance • Can access only static members of outer class 3. Local Inner Class • Defined inside a method or block • Scope is limited to that method • Cannot be accessed outside 4. Anonymous Inner Class • No class name • Used for one-time implementations • Common with interfaces / abstract classes --- 🔹 Key Differences • Member vs Static → Depends on outer instance • Local vs Anonymous → Named vs unnamed + scope • Static nested is not truly “inner” (no outer dependency) --- 🔹 Access Behavior • Inner classes can access outer class variables directly • Even private members are accessible • Anonymous & local classes can access effectively final variables --- 🔹 Syntax Example class Outer { private int x = 10; class Inner { void display() { System.out.println(x); } } } --- 🔹 When to Use ✔ When a class is tightly coupled with another ✔ When functionality should be hidden from outside ✔ When improving readability and maintainability --- 🔹 When NOT to Use ✖ When classes are reusable independently ✖ When it increases complexity unnecessarily --- 💡 In short: Inner classes help you write cleaner, more structured, and encapsulated Java code — when used correctly. --- #Java #OOP #Programming #SoftwareDevelopment #Coding
To view or add a comment, sign in
-
🚀 Day 34 – Core Java | Constructor Chaining & Inheritance Internals Today’s session focused on one of the most misunderstood concepts in Java OOP — Constructor Chaining during Inheritance. We explored how constructors behave when parent and child classes interact during object creation. 🔹 Two Important Rules of Inheritance ✔ Private members do NOT participate in inheritance Reason: Encapsulation protects sensitive data. Allowing private members to be inherited would break security. Example: private int accountNumber; private int pin; A child class cannot access these variables directly. ✔ Constructors do NOT participate in inheritance A constructor belongs only to its class. Example: class Parent { Parent() { } } class Child extends Parent { } The child class does not inherit the parent constructor. 🔹 Then Why Does Parent Constructor Execute? When a child object is created, Java automatically performs constructor chaining. Java inserts this statement automatically: super(); This calls the parent class constructor before executing the child constructor. Execution flow: Child Object Creation ↓ Child Constructor ↓ super() ↓ Parent Constructor ↓ Child Constructor continues 🔹 Constructor Chaining Types 1️⃣ Local Constructor Chaining Occurs within the same class Uses: this() Example: class Test { Test() { this(10); } Test(int x) { System.out.println(x); } } 2️⃣ Parent Constructor Chaining Occurs between parent and child classes Uses: super() Example: class Parent { Parent() { System.out.println("Parent constructor"); } } class Child extends Parent { Child() { System.out.println("Child constructor"); } } Output: Parent constructor Child constructor 🔹 Important Rules ✔ The first line of every constructor must be either: this() or super() ✔ Both cannot exist together in the same constructor. ✔ If you write nothing, Java automatically inserts: super(); 🔹 Default Parent of Every Class Every class in Java implicitly extends Object class. class Example extends Object So constructor flow always ends at: Object() which is the root of the Java class hierarchy. 💡 Biggest Takeaway Understanding constructor chaining helps you clearly understand: Object creation flow Parent–child class interaction JVM execution behavior Real interview questions on inheritance This concept is heavily used in frameworks, large-scale applications, and interview coding rounds. #Day34 #CoreJava #Inheritance #ConstructorChaining #JavaOOP #JavaInternals #DeveloperLearning #JavaJourney
To view or add a comment, sign in
-
Generic Classes in Java – Clean Explanation with Examples 🚀 Generics in Java are a compile-time type-safety mechanism that allows you to write parameterized classes, methods, and interfaces. Instead of hardcoding a type, you define a type placeholder (like T) that gets replaced with an actual type during usage. 🔹Before Generics (Problem): class Box { Object value; } Box box = new Box(); box.value = "Hello"; Integer x = (Integer) box.value; // Runtime error ❌ Issues: • No type safety • Manual casting required • Errors occur at runtime 🔹With Generics (Solution): class Box<T> { private T value; public void set(T value) { this.value = value; } public T get() { return value; } } 🔹Usage: public class Main { public static void main(String[] args) { Box<Integer> intBox = new Box<>(); intBox.set(10); int num = intBox.get(); // ✅ No casting Box<String> strBox = new Box<>(); strBox.set("Hello"); String text = strBox.get(); } } 🔹Bounded Generics: 1.Upper Bound (extends) → Read Only: Restricts type to a subclass List<? extends Number> list; ✔ Allowed: Integer, Double ❌ Not Allowed: String 👉 Why Read Only? You can safely read values as Number, but you cannot add specific types because the exact subtype is unknown at compile time. 2.Lower Bound (super) → Write Only: Restricts type to a superclass List<? super Integer> list; ✔ Allowed: Integer, Number, Object ❌ Not Allowed: Double, String 👉 Why Write Only? You can safely add Integer (or its subclasses), but when reading, you only get Object since the exact type is unknown. 🔹Key Takeaway: Generics = Type Safety + No Casting + Compile-Time Errors Clean code, fewer bugs, and better maintainability - that’s the power of Generics 💡 #Java #Generics #Programming #SoftwareEngineering #Coding
To view or add a comment, sign in
-
⏳ Day 15 – 1 Minute Java Clarity – static Keyword in Java One keyword… but it changes everything! ⚡ 📌 What is static? When something is static, it belongs to the CLASS — not to any object. 👉 All objects share the same static member. 📌 Static Variable: class Student { String name; static String school = "Java Academy"; } 👉 Every student object shares the same school name. ✔ Memory created only ONCE in Method Area. 📌 Static Method: class MathUtils { static int square(int n) { return n * n; } } MathUtils.square(5); // No object needed! ⚠️ Static methods CANNOT access non-static variables directly. ⚠️ this keyword is NOT allowed inside static methods. 📌 Static Block: static { System.out.println("Runs before main()!"); } 👉 Executes ONCE when class loads — even before main() runs! ✔ Used for one-time setup like DB config loading. 💡 Real-time Example: Think of a company: Every employee has their own name → non-static But company name is the same for all → static ✅ ⚠️ Interview Trap: Why is main() static? 👉 JVM calls main() without creating any object. If main() wasn't static — who would create the object first? 🤔 💡 Quick Summary ✔ static = belongs to class, not object ✔ Static block runs before main() ✔ Static methods can't use this or non-static members 🔹 Next Topic → final keyword in Java Did you know static block runs before main()? Drop 🔥 if this was new! #Java #JavaProgramming #StaticKeyword #CoreJava #JavaDeveloper #BackendDeveloper #Coding #Programming #SoftwareEngineering #LearningInPublic #100DaysOfCode #ProgrammingTips #1MinuteJavaClarity
To view or add a comment, sign in
-
-
🚀 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
-
Day 22 – Reference Variables in Java Today I explored an important concept in Object-Oriented Programming — Reference Variables. Unlike primitive variables, reference variables store the address of an object, not the actual value. 🔹 What is a Reference Variable? A reference variable is a non-primitive variable that refers to an object created from a class. It is declared using the class name. Syntax: ClassName referenceVariable; Initialization- referenceVariable = new ClassName(); Or both together: ClassName referenceVariable = new ClassName(); Here: ClassName → Name of the class referenceVariable → Object reference new → Keyword used to create an object ClassName() → Constructor 🔹 Example class Demo5 { int x = 100; int y = 200; } class MainClass3 { public static void main(String[] args) { Demo5 d1 = new Demo5(); System.out.println("x = " + d1.x); System.out.println("y = " + d1.y); System.out.println("modifying x & y"); d1.x = 300; d1.y = 400; System.out.println("x = " + d1.x); System.out.println("y = " + d1.y); } } Output: x = 100 y = 200 modifying x & y x = 300 y = 400 🔹 Important Observation When we write: Demo5 d1 = new Demo5(); Java performs three things: 1️⃣ Creates a reference variable (d1) 2️⃣ Creates a new object in memory 3️⃣ Stores the object reference in the variable #Java #CoreJava #JavaFullStack #OOP #Programming #BackendDevelopment #LearningInPublic #SoftwareDevelopment
To view or add a comment, sign in
-
-
Understanding the Java "main()" Method — "public static void main(String[] args)" Every Java program starts execution from the main() method. When you run a Java program, the JVM (Java Virtual Machine) looks for this method as the entry point. If a program does not contain a valid "main()" method, the JVM will not start execution. The commonly used syntax is: public static void main(String[] args) Each word in this declaration has a specific purpose: • public → Access modifier that allows the JVM to call the method from outside the class. If it is not public, the JVM cannot access it. • static → Allows the method to be called without creating an object of the class. The JVM can directly invoke the method when the program starts. • void → Specifies that the method does not return any value. Once the main method finishes execution, the Java program terminates. • main → The method name recognized by the JVM as the starting point of the program. Changing this name prevents the program from running. • String[] args → An array that stores command-line arguments passed when running the program. Example: class Example { public static void main(String[] args) { System.out.println("Hello, Java!"); } } Java also allows equivalent forms like: public static void main(String args[]) public static void main(String... args) All of these work because the parameter is still treated as a String array. Key Takeaway: The "main()" method acts as the entry point of a Java application, allowing the JVM to begin executing the program. #Java #JavaProgramming #CoreJava #JVM #BackendDevelopment #Programming #LearnToCode
To view or add a comment, sign in
-
-
💡 Sneaky Throws in Java — A Lesser-Known Exception Handling Trick Java’s exception system distinguishes between checked and unchecked exceptions. Normally, checked exceptions like IOException must be either caught or declared in the method signature using throws. But there is an interesting technique called Sneaky Throws that allows a method to throw a checked exception without declaring it. 🔎 How does it work? The trick relies on Java generics and type erasure. A generic method can be written like this: public static <E extends Throwable> void sneakyThrow(Throwable e) throws E { throw (E) e; } At compile time, the compiler infers E as an unchecked type (often RuntimeException). However, at runtime the JVM simply executes the throw instruction and throws the actual exception object. ⚙️ Why developers use it Sneaky throws is sometimes useful when dealing with: Lambda expressions Streams Functional interfaces that don’t allow checked exceptions Utility libraries that want to reduce boilerplate try-catch blocks Example use case: private static void throwSneakyIOException() { sneakyThrow(new IOException("Sneaky exception")); } The method does not declare throws IOException, yet it will still throw it at runtime. ⚠️ Why it’s controversial While powerful, it breaks the normal exception contract of Java: Method signatures no longer reveal possible checked exceptions Harder for callers to know what to handle Can reduce code clarity Because of this, many teams avoid it in public APIs. 📦 Libraries like Project Lombok even provide an annotation for it: @SneakyThrows ✅ Takeaway Sneaky throws demonstrates an interesting reality of Java: The compiler enforces checked exceptions, but the JVM does not distinguish them at runtime. It’s a clever trick that shows how generics, type inference, and the JVM execution model interact under the hood. #Java #ExceptionHandling #JavaInternals #BackendDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
The Magic of @SneakyThrows in Java: How Does It Break the Rules? Lombok’s @SneakyThrows often raises questions in code reviews. It allows us to throw a checked exception (like IOException) without adding a throws clause - something Java normally forbids. The Problem: Java forces you to catch checked exceptions or declare them. This is especially frustrating with lambdas, where adding a throws declaration isn't an option. How does this work? Lombok uses bytecode manipulation. It replaces your checked exception with a generic throw that bypasses the compiler's checks. At runtime, the exception is thrown normally, but the compiler never sees the violation. It’s a clean solution for edge cases - just use it intentionally. While @SneakyThrows makes the code look cleaner, it breaks the method signature contract. Consumers of your method won't know they need to handle that exception, which can lead to unexpected application crashes. It also violates the Principle of Least Astonishment - other developers reading the code won't expect a checked exception to appear out of nowhere, making debugging and maintenance more difficult. But despite these risks, it's hard to deny how pleasant @SneakyThrows feels to use. The code becomes so clean and readable - no more wrapping everything in try-catch blocks just to satisfy the compiler. When you're working with streams or quick scripts, that single annotation removes the noise and lets the business logic shine. Do you use @SneakyThrows in your projects? Let’s discuss below! 👇 #Java #Programming #Lombok #SoftwareDevelopment #CodingTips
To view or add a comment, sign in
-
-
Day 21 – Accessing Non-Static Members of a Class in Java Yesterday I explored static members in Java. Today’s concept was the opposite side of it: 👉 Non-Static Members (Instance Members) Unlike static members, non-static members belong to objects, not the class itself. That means we must create an object of the class to access them. 🔹 Syntax new ClassName().memberName; or ClassName obj = new ClassName(); obj.memberName; 🔹 Example class Demo4 { int x = 100; int y = 200; void test() { System.out.println("running test() method"); } } class MainClass2 { public static void main(String[] args) { System.out.println("x = " + new Demo4().x); System.out.println("y = " + new Demo4().y); new Demo4().test(); } } Output x = 100 y = 200 running test() method 🔹 Important Observation Every time we write: new Demo4() ➡️ A new object is created. Each object has its own copy of non-static variables. This is why instance variables are object-specific, unlike static variables which are shared across objects. 📌 Key takeaway • Static members → belong to the class • Non-static members → belong to objects • Accessing instance members requires object creation Understanding this concept is essential for mastering Object-Oriented Programming in Java. Step by step building stronger Core Java fundamentals. #Java #CoreJava #JavaFullStack #OOP #Programming #BackendDevelopment #LearningInPublic #SoftwareDevelopment
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