Class in Java

In Java, a class is a blueprint or template that defines the properties and behavior of an object. A class contains fields (also called instance variables) that represent the object's state, and methods that define the object's behavior. When a class is instantiated, an object is created that has the same properties and behavior as the class.

Here is an example of a simple Java class:

                
    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 void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

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

        public void sayHello() {
            System.out.println("Hello, my name is " + name);
        }
    }
                
            

In this example, the Person class has two private fields, name and age, and three public methods: a constructor that takes a name and age as parameters and sets the corresponding fields, and getName() and getAge() methods that return the values of the corresponding fields. The setName() and setAge() methods are also public and allow the fields to be modified from outside the class.

The sayHello() method is also public, and it simply prints a message to the console that includes the person's name.

To create an instance of the Person class and call its methods, we can do the following:

                
    Person john = new Person("John", 30);
    john.sayHello();
    System.out.println(john.getName() + " is " + john.getAge() + " years old.");
    john.setAge(31);
    System.out.println(john.getName() + " is now " + john.getAge() + " years old.");
                
            

This will output:

                
    Hello, my name is John
    John is 30 years old.
    John is now 31 years old.
                
            

In summary, a Java class is a fundamental concept of object-oriented programming that allows developers to create objects with specific properties and behavior. Classes are templates or blueprints for objects, and they contain fields that represent the object's state, and methods that define the object's behavior.