通过对象实例访问静态方法 [英] Accessing static method through an object instance

查看:55
本文介绍了通过对象实例访问静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解到,如果我们想调用另一个类的静态方法,那么您必须在调用静态方法时写出类名.在下面的程序中,我在 Employee_Impl 类中创建了 Employee 类的对象,并使用该对象,我仍然能够访问 count 方法.如果仅使用类名访问 static 方法,为什么它允许我通过对象使用 count 方法?这是否意味着可以使用对象和类名访问静态方法?

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());        
    }
}

输出

1
2
3

推荐答案

编译器自动通过调用您的变量(不是>价值!).请注意,即使您的对象为空,它会起作用,也不会抛出 NullPointerException.

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.

这篇关于通过对象实例访问静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆