What is variable shadowing used for in a Java class?

后端 未结 5 1417
春和景丽
春和景丽 2020-11-22 14:53

I\'m reading my Deitel, Java How to Program book and came across the term shadowing. If shadowing is allowed, what situation or what purpose is there for it in a Ja

5条回答
  •  孤城傲影
    2020-11-22 14:55

    The two common uses are constructors and set methods:

    public Foo(int x) {
        this.x = x;
    }
    
    public void setX(int x) {
        this.x = x;
    }
    

    Very occassionally it's useful if you want a copy of the variable at a single instant, but the variable may change within the method call.

    private void fire() {
        Listener[] listeners = this.listeners;
        int num = listeners.length;
        for (int ct=0; ct

    (Of course, a contrived example made unnecessary with the posh for loop.)

提交回复
热议问题