Yes. In order for a plan to be followed, it has to somehow exist.
When a Java application is run, objects are created and their methods are invoked (are run). To create an object, there needs to be a description of it.
A class is a description of a kind of object. A programmer may define a class using Java, or may use predefined classes that come in class libraries.
A class is merely a plan, or template, for a possible object.
It does not by itself create any objects.
When a programmer wants to create an object
the new
operator is used with the name of the class.
Creating an object is called instantiation.
Attributes are variables that store data within a class.
A constructor is a special method used for initializing objects when they are created. In Java, the constructor has the same name as the class. Constructors can have parameters to initialize object attributes.
Methods are functions or procedures that define the behavior of a class. The define what the object can "do."
Example:
public class Car {
// Attributes
String brand;
String color;
int year;
// Constructor
public Car(String brand, String color, int year) {
this.brand = brand;
this.color = color;
this.year = year;
}
// Method
public void start() {
System.out.println("The " + color + " " + brand + " starts.");
}
}
public class Main {
public static void main(String[] args) {
// Creating objects of the Car class
Car car1 = new Car("Toyota", "Blue", 2020);
Car car2 = new Car("BMW", "Red", 2018);
// Accessing object attributes
System.out.println(car1.brand); // Output: Toyota
// Calling object methods
car2.start(); // Output: The Red BMW starts.
}
}
Recall the three properties of objects: identity, state, and behavior. Do you expect that a class definition will have its own state and behavior?