Introduce Java Class Attributes and give examples
In Java, class attributes (also known as fields or member variables) are variables that are declared within a class but outside any method. They represent the state or properties of an object created from that class. Class attributes can have different access modifiers (like private
, public
, protected
, or package-private) that determine their visibility and accessibility.
int
, double
, char
, etc.) and reference types (like objects).Here’s a simple example to illustrate class attributes in Java:
public class Car {
// Instance variables (attributes)
private String make; // The make of the car
private String model; // The model of the car
private int year; // The year of manufacture
private double price; // The price of the car
// Static variable (shared among all instances)
private static int numberOfCars = 0; // Keeps track of the number of Car instances
// Constructor
public Car(String make, String model, int year, double price) {
this.make = make;
this.model = model;
this.year = year;
this.price = price;
numberOfCars++; // Increment the number of cars whenever a new car is created
}
// Getter methods
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public int getYear() {
return year;
}
public double getPrice() {
return price;
}
public static int getNumberOfCars() {
return numberOfCars;
}
// Method to display car details
public void displayCarInfo() {
System.out.println("Car Make: " + make);
System.out.println("Car Model: " + model);
System.out.println("Year: " + year);
System.out.println("Price: $" + price);
}
}
Instance Variables:
make
, model
, year
, and price
are instance variables that hold the state of each Car
object.private
, meaning they cannot be accessed directly from outside the class.Static Variable:
numberOfCars
is a static variable that keeps track of how many Car
objects have been created. It is shared among all instances of the Car
class.Constructor:
numberOfCars
each time a new Car
object is created.Getter Methods:
Display Method:
displayCarInfo()
is a method that prints the details of the car.Here’s how you might use the Car
class in a main method:
public class Main {
public static void main(String[] args) {
Car car1 = new Car("Toyota", "Camry", 2020, 24000);
Car car2 = new Car("Honda", "Civic", 2021, 22000);
car1.displayCarInfo();
System.out.println();
car2.displayCarInfo();
System.out.println("Total number of cars: " + Car.getNumberOfCars());
}
}
Car Make: Toyota
Car Model: Camry
Year: 2020
Price: $24000.0
Car Make: Honda
Car Model: Civic
Year: 2021
Price: $22000.0
Total number of cars: 2
This example demonstrates how class attributes are used to define the properties of an object and how they can be accessed and manipulated through methods.