In Java, a class is a blueprint or template for creating objects. It defines a set of attributes and methods that are common to all objects of a certain type.
A class contains fields, which represent the attributes or data of an object, and methods, which define the behavior of the object. For example, a Person
class might have fields like name
, age
, and gender
, and methods like getName()
, getAge()
, setAge()
, etc.
When you create an object of a class, you are creating an instance of that class. You can then use the methods and fields of the object to perform operations and store data.
Here is an example of a simple class in Java:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
In this example, we have defined a Person
class with fields for name
and age
, and methods for getting and setting those fields. We have also defined a constructor method that sets the initial values for the fields when a new Person
object is created.