DAY 5. I am trying to strength by Core java basic its one of the concepts I struggle to understand. here is everthing I learnt today about static keyword in java
Java Summary: Static, Class Loading & Execution Flow
1. static Keyword in Java
Definition:
The static keyword means the member belongs to the class itself, not to instances.
class CarFactory {
// Static variable shared by all cars made by any factory
static int totalCarsProduced = 0;
// Static block: runs once when the class is loaded
static {
System.out.println("CarFactory class loaded. Initializing factory...");
}
// Instance variable (per car)
String model;
// Constructor increments total cars produced
CarFactory(String model) {
this.model = model;
totalCarsProduced++;
}
// Static method: calculates price without needing an object
static int calculatePrice(String model, int basePrice) {
if ("Luxury".equalsIgnoreCase(model)) {
return basePrice + 7000;
} else {
return basePrice;
}
}
// Static nested class representing a part of the car
static class Engine {
void start() {
System.out.println("Engine started.");
}
}
}
public class Main {
public static void main(String[] args) {
// Class loaded, static block runs first
// Create cars (instances)
CarFactory car1 = new CarFactory("Standard");
CarFactory car2 = new CarFactory("Luxury");
// Access static variable shared by all cars
System.out.println("Total cars produced: " + CarFactory.totalCarsProduced); // 2
// Call static method without creating an object
int price = CarFactory.calculatePrice("Luxury", 25000);
System.out.println("Price of Luxury car: $" + price); // 32000
// Create and use static nested class (no CarFactory instance needed)
CarFactory.Engine engine = new CarFactory.Engine();
engine.start();
}
}
Where static Can Be Used:
Static variable → Shared among all instances (1 copy in memory)
Static method → Can be called without object creation; can't access instance members directly
Static block → Runs once when class is loaded; used to initialize static fields. they cant return anything.
Static nested class → Class inside another class; does NOT need outer class object
Static Nested Class vs Inner Class
Static Nested Class
Inner (Non-Static) Class
Access only static members of outer class
Can access all members of outer class
Does NOT require outer class instance
Requires outer class instance
Can be instantiated independently
Must be tied to an outer class object
Key Rules:
Static methods can't access instance fields or methods directly.
Static methods can't be abstract.
Static methods can't be overridden (they're hidden instead).
Static blocks and variables execute in order of appearance.
2. Class Loading & Initialization
What Is Class Loading?
Class loading is the process of bringing .class files into memory using a ClassLoader.
Top comments (0)