Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static method invocation

Can we call a static method without mentioning the class name in Java?

like image 438
user315459 Avatar asked Apr 13 '10 12:04

user315459


People also ask

How is static method invoked?

We can invoke a static method by using its class reference. An instance method is invoked by using the object reference.

What is static method invocation in Java?

A static method in Java (also called class method) is a method that belongs to the class and not the instance. Therefore, you can invoke the method through the class instead of creating an instance first and calling the method on that instance.

Can a static method be invoked by an instance?

A static method cannot access a class's instance variables and instance methods, because a static method can be called even when no objects of the class have been instantiated.

What is a static method?

A static method (or static function) is a method defined as a member of an object but is accessible directly from an API object's constructor, rather than from an object instance created via the constructor.


1 Answers

Yes you can. Check out static imports. You have to mention the class name in the import statement, but after that you don't have to.e.g. from the linked article:

import static java.lang.Math.abs;
import static java.lang.Math.max;

int xDist = abs(destination.getX() - x);
int yDist = abs(destination.getY() - y);
return max(xDist, yDist);

Introduced in Java 5.

like image 131
Brian Agnew Avatar answered Oct 14 '22 11:10

Brian Agnew