开发者

Inheritance and method scope in Java

开发者 https://www.devze.com 2023-04-08 23:15 出处:网络
In the following example pseudocode: public class MyPanel extends JPanel { public void reset() { this.clear();

In the following example pseudocode:

public class MyPanel extends JPanel {
    public void reset() {
        this.clear();
        clear();
    }
    public void clear() { System.out.println("FAIL"); }
};

public class MySpecialPanel extends MyPanel {
    public void clear() { System.out.println("Hello, world"); }
};

When calling (new MySpecialPanel()).re开发者_如何学Goset() shouldn't both this.clear() and clear() resolve in the same scope? Is there any difference between this.clear() and clear()?


public void reset() {
    this.clear();
    clear();
}

In the code above, that calls the same method twice. There is no difference between clear() and this.clear().

You can explicitly call the superclasses method with super.clear().


There is no difference between this.clear() and clear().

You have a MySpecialPanel object and the clear() method on that object is called twice. To call the superclass's clear, you must use super.clear()

So, you do something like this --

public void reset() {
        clear();
        super.clear();
}


in your code:

public void reset() {
    this.clear();
    clear();
}

both this.clear() and clear() are the same.

this is a keyword for setting the scope of the call inside the class itself super sets the scope to the class itself and the superclass


Stating the obvious as many have already responded - when you call clear() on an object, that object is in scope; when you use this you are referring to that same object in context.

0

精彩评论

暂无评论...
验证码 换一张
取 消