A class is a blueprint or a template for creating objects. It defines the properties and behaviors that objects of the class will have. An object, on the other hand, is an instance of a class. Objects are created based on the structure defined by the class.
// Defining a class
public class Car {
// Properties or fields
String brand;
String model;
int year;
// Constructor (a special method to initialize objects)
public Car(String brand, String model, int year) {
this.brand = brand;
this.model = model;
this.year = year;
}
// Method (a function associated with the class)
public void displayInfo() {
System.out.println("Brand: " + brand);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
}
}
// Creating objects of the Car class
public class Main {
public static void main(String[] args) {
// Creating two Car objects
Car car1 = new Car("Toyota", "Camry", 2022);
Car car2 = new Car("Honda", "Civic", 2021);
// Calling methods on objects
car1.displayInfo();
System.out.println(); // Adding a line break
car2.displayInfo();
}
}
In this example, we have a class named Car
with three properties (brand, model, and year), a constructor to initialize the object, and a method (displayInfo
) to display information about the car. In the Main
class, we create two instances of the Car
class (car1
and car2
) and then call the displayInfo
method on each of them.
Key concepts related to classes and objects in Java:
- Class: A blueprint or template that defines the structure and behavior of objects.
- Object: An instance of a class. It is a real-world entity that can be uniquely identified.
- Constructor: A special method used for initializing objects. It has the same name as the class and is called when an object is created.
- Method: Functions defined within a class that represent the behavior of objects.
- Field or Property: Variables that represent the attributes or characteristics of objects.
Комментариев нет:
Отправить комментарий