Key Characteristics:
static
Keyword: Static variables are declared using the static
keyword.Key Characteristics:
this
Keyword: In static methods, the this
keyword cannot be used.public class Car {
private String brand;
private String model;
private int year;
// Static variable
private static int numberOfCars = 0;
// Constructor
public Car(String brand, String model, int year) {
this.brand = brand;
this.model = model;
this.year = year;
numberOfCars++; // Increment static variable
}
// Static method to get the number of cars
public static int getNumberOfCars() {
return numberOfCars;
}
// Instance method to display car details
public void displayDetails() {
System.out.println("Brand: " + brand);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
}
public static void main(String[] args) {
Car car1 = new Car("Toyota", "Camry", 2020);
Car car2 = new Car("Honda", "Accord", 2021);
car1.displayDetails();
System.out.println();
car2.displayDetails();
System.out.println();
// Access static variable using class name
System.out.println("Total number of cars: " + Car.getNumberOfCars());
}
}
Brand: Toyota
Model: Camry
Year: 2020
Brand: Honda
Model: Accord
Year: 2021
Total number of cars: 2