声明引用时是否加载了类? [英] Is the class loaded when it's reference is declared?

查看:87
本文介绍了声明引用时是否加载了类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建对类对象的引用会导致该类被加载吗? 加载类时会初始化静态变量,因此考虑以下代码,答案是否定的,对吗?

Does creating a reference to an object of a class cause the class to be loaded ? Static variables are initialized when the class is loaded, so considering the following code the answer is no, am I right?

    class A{
        static int f(){
            System.out.println("initializing!");
            return 0;
        }
        static final int i = f();
    }
    public class Main {
        public static void main(String[] args) {
            A a;
        }
    }

代码没有输出.

推荐答案

是.调用类方法或实例化实例时,将调用静态初始化器.

Yes. Static initializers are called when a class method is called or an instance is instantiated.

从您的示例中,您可以执行以下操作之一:

From your example you can do one of the following:

public static void main(String[] args) {
    A a = new A();
}

2.调用静态类方法

public static void main(String[] args) {
    int f = A.f();
}

这篇关于声明引用时是否加载了类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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