DEV Community

Ligouri S Tittus
Ligouri S Tittus

Posted on

Class, Object, and Method in Java

Class
A class serves as a blueprint or template for creating objects. It defines the structure and behavior that objects of that class will possess. A class encapsulates data (fields or attributes) and the operations that can be performed on that data (methods). It is a logical entity and does not consume memory until an object is created from it.

Components of Java Classes

  1. Class keyword: Class keyword is used to create a class.
  2. Class name: The name should begin with an initial letter (capitalized by convention).

Object
An object is an instance of a class. It is a concrete realization of the blueprint defined by the class. Objects have a state (values of their fields) and exhibit behavior (actions performed by their methods). When an object is created, memory is allocated for it.

  1. State: It is represented by attributes of an object. It also reflects the properties of an object.
  2. Behavior: It is represented by the methods of an object. It also reflects the response of an object with other objects.
  3. Identity: It gives a unique name to an object and enables one object to interact with other objects.

Method
A method is a block of code within a class that defines a specific behavior or action that an object of that class can perform. Methods can manipulate the object's data, perform calculations, or interact with other objects. They provide the functionality of an object.

Types of methods

  1. Void Method

A void method does not return any value. It simply performs a task, like printing something or modifying an object’s state.

Example:
class Main {
// Void method
void greet() {
System.out.println("Hello");
}

public static void main(String[] args) {
    Main obj = new Main(); // create object
    obj.greet();           // call void method
}
Enter fullscreen mode Exit fullscreen mode

}

  1. Return Type Method

A return type method performs a task and returns a value to the caller. You must specify the type of value it returns (int, String, boolean, etc.)

Example:

class Main {
// Return type method
int add(int a, int b) {
return a + b;
}

public static void main(String[] args) {
    Main obj = new Main();          // create object
    int sum = obj.add(5, 10);      // call method and get returned value
    System.out.println("Sum = " + sum);
}
Enter fullscreen mode Exit fullscreen mode

}

Reffered (https://www.geeksforgeeks.org/java/classes-objects-java/)

Top comments (0)