问题
I have learnt that if we wish to call static method of another class then you have to write class name while calling static method. In below program, I created object of the Employee class inside Employee_Impl class and using that object, I was still able to access the count
method. Why is it allowing me to use count
method through an object if static
methods are accessed using only class name? Does that mean static methods can be accessed using objects as well as class name, both?
Employee.java
public class Employee{
static int counter = 0;
static int count(){
counter++;
return counter;
}
}
Employee_Impl.java
class Employee_Impl
public static void main(String args[]){
Employee obj = new Employee();
System.out.println(obj.count());
System.out.println(Employee.count());
System.out.println(obj.count());
}
}
output
1
2
3
回答1:
Compiler automatically substitutes this call by call by class name of your variable (not of it's value!). Note, even if your object would be null, it will work, no NullPointerException
is thrown.
回答2:
You are allowed to do this because you made an instance of Employee
to access the method through.
The point of static methods is to allow access to "utility methods" that can be invoked without the overhead of instantiating a new object. Furthermore, these methods can be shared by any instance of the class Employee
and can mutate shared static variables or attributes. For example, pretend the shared prefix of all Employee
objects was maintained as a static attribute:
public class Employee {
private static String EMPLOYEE_IDENTIFIER_PREFIX = "Acme Corporation Employee Number:"
public static void setEmployeeIdentifierPrefix(String prefix){
Employee.EMPLOYEE_IDENTIFIER_PREFIX = prefix;
}
}
If AcmeCorporation
was purchased by MultinationalCorporation
the prefix can be updated for all Employee
objects by using the setEmployeeIdentifierPrefixMethod
on the class like so:
Employee.setEmployeeIdentifierPrefix("Multinational Corporation Employee Number:");
回答3:
Static methods are always executes from class...not from objects...
here.., even though you are calling count()
method on object obj.count()
it will executes from Employee
class only...
first it will identify the class of object then from that object type it will execute the count()
method.
来源:https://stackoverflow.com/questions/32039657/accessing-static-method-through-an-object-instance