有关编程的菜鸟问题

先上代码


convertView.setOnClickListener(new OnClickListener() {

    long lastClick;

    @Override

    public void onClick(View v) {

        if (System.currentTimeMillis() - lastClick <= 1000) {

        return;

        }

    lastClick = System.currentTimeMillis(); 

    }

});

这样写是编译通过的,但是如果我把long lastClick;放到onClick的里面第一行,然后再进行if来判断,就会报错要求对lastClick进行初始化,这时为什么啊?求解


眼眸繁星
浏览 429回答 1
1回答

茅侃侃

long lastClick放在 函数外, 是对象的成员变量, 默认初始化为0.放在函数内, 称为本地变量. JLS7, #16 里有写:"EACH local variable (§14.4) and every blank final field (§4.12.4,§8.3.1.2) must have a definitely assigned value when any access of itsvalue occurs. An access to its value consists of the simple name ofthe variable (or, for a field, the simple name of the field qualifiedby this) occurring anywhere in an expression except as the left-handoperand of the simple assignment operator = (§15.26.1).&nbsp;For everyaccess of a local variable or blank final field x, x must bedefinitely assigned before the access, or a compile-time error occurs"
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java