Classes and Objects in Java

In the Java programming language, a class is a template that defines the structure and behavior of an object. A class consists of two main components: instance variables and methods.

Instance variables (also known as fields or attributes) are variables that store the data associated with an object. They represent the state of the object and are defined within the class. For example, a Person class might have instance variables for the person’s name, age, and address.

Methods are functions that define the behavior of an object. They are defined within the class and operate on the object’s instance variables. For example, a Person class might have methods for setting and getting the person’s name, age, and address, as well as methods for performing other actions such as greeting someone or printing the person’s information.

Here is an example of a simple class in Java:


public class Person {
// instance variables
private String name;
private int age;
private String address;

// constructor
public Person(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}

// methods
public void setName(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void setAge(int age) {
this.age = age;
}

public int getAge() {
return age;
}

public void setAddress(String address) {
this.address = address;
}

public String getAddress() {
return address;
}

public void greet() {
System.out.println("Hi, my name is " + name + " and I am " + age + " years old.");
}

public void printInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Address: " + address);
}
}

This class defines a Person object with three instance variables: name, age, and address. It also has a constructor, which is a special method that is used to create a new instance of the Person class. The constructor takes three arguments: name, age, and address, and assigns them to the corresponding instance variables.

The class also has methods for setting and getting the person’s name, age, and address, as well as a greet() method that prints a greeting message to the console and a printInfo() method that prints the person’s information.

To create a new Person object, you can use the new keyword and the constructor:


Person p1 = new Person("Alice", 21, "123 Main St.");

This creates a new Person object with the name “Alice”, age 21, and address “123 Main St.”.

To call the greet() method on the Person object, you can use the following syntax:


p1.greet();

This will print the message “Hi, my name is Alice and I am 21 years old.” to the console.

To call the printInfo() method on the Person object, you can use the following syntax:


p1.printInfo();