this and super keywords in Java

The two keywords, this and super to help you explicitly name the field or method that you want. Using this and super you have full control on whether to call a method or field present in the same class or to call from the immediate superclass. This keyword is used as a reference to the current object which is an instance of the current class.

The keyword super also references the current object, but as an instance of the current class’s super class.
The this reference to the current object is useful in situations where a local variable hides, or shadows, a field with the same name. If a method needs to pass the current object to another method, it can do so using the this reference. Note that the this reference cannot be used in a static context, as static code is not executed in the context of any object.

class Counter {
    int i = 0;

    Counter increment() {
        i++;
        return this;
    }

    void print() {
        System.out.println("i = " + i);
    }
}

public class CounterDemo extends Counter {
    public static void main(String[] args) {
        Counter x = new Counter();
        x.increment().increment().increment().print();
    }
}

 

Output:
Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0

3 comments:

Sandeep said...

another usage of
this and super keyword
is to invoke other constructors from a single constructor.

hitesh kumar said...

Super keyword in java

Thanks for this post

James Robert said...

Nice informative post .I think also this reference to the present question is helpful in circumstances where a neighborhood variable stows away, or shadows, a field with a similar name.

Magento Connector

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More