How can Java invoke a class method?

In Java, calling a class method requires using the class name to make the call. Here are some common ways to call a class method.

  1. Call class methods directly using class name:
ClassName.methodName(arguments);

For example, if there is a class named Math that has a static method called max(), it can be called as follows:

int maxNumber = Math.max(5, 10);
  1. Call a class method using the object’s name.

If an object of a class has already been created, you can also use the object’s name to call the class method. In this case, the compiler will automatically use the class to which the object belongs to call the method.

ClassName objectName = new ClassName();
objectName.methodName(arguments);

For example, if there is a class named String that has a static method called valueOf(), it can be called in the following way:

String str = new String.valueOf(10);

However, this method is not common, as typically class methods are called directly using the class name.

It is important to note that class methods are associated with the class itself, not with instances of the class. Therefore, the effect of calling a class method is the same whether done through the class name or object name.

bannerAds