this and super - Keywords

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

People who read this post also read :



3 comments:

Appreciate your work and would like to thank you for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well.

sap project

It feels very nice when someone hails your work.This kind of comment just boost me and i get power to do more and more work......@Tani

wanted to share a trick:
If you want some code to be executed before the call to this and super, you can include the same as part of the argument to this() and super(). See more at:
this and super keywords

Post a Comment

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More