In Java, a class is a blueprint for creating objects that share common properties and behavior. A class defines the data members (fields) and member functions (methods) that an object of that class will have. Here’s 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 sayHello() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
}
This Person
class has two private fields (name
and age
) and three public methods (Person()
, getName()
, getAge()
, and sayHello()
). The Person()
method is a constructor that initializes the name
and age
fields when a Person
object is created. The getName()
and getAge()
methods are getter methods that allow you to retrieve the name
and age
fields, respectively. The sayHello()
method is a behavior that prints a message to the console.
To create an object of the Person
class, you can use the new
operator and call the constructor with the appropriate arguments:
Person person = new Person("Alice", 30);
This creates a new Person
object with the name “Alice” and age 30. You can then call the object’s methods to access its data and behavior:
String name = person.getName();
int age = person.getAge();
person.sayHello(); // prints "Hello, my name is Alice and I am 30 years old."
Objects of the same class share the same data members and member functions, but each object has its own copy of the data members. This means that you can create multiple Person
objects with different data, and each object can behave independently. Classes and objects are a fundamental concept in object-oriented programming, and they allow you to write modular and reusable code.