In a class that implements and extends other classes, use the Java "this" keyword.

  • So I'm attempting to learn more about the "this" term. I realize that the term "this" relates to the current object. The object whose constructor or function is being invoked .

    So, if I use "this.setLayout," would it look for an object that has the "setLayout" method ?

    Assume I extend a class and include other classes in my superclass. Will "this" look for the method in all implemented and extended classes as stated on this page?

    Consider my class:

    public class GUI extends JPanel implements Runnable, ActionListener

    and I employ:

    this.setLayout();

    So the compiler will look for the method "setLayout" in all extended and implemented classes until it finds it in Jpanel? I just want to understand how "this" knows what I am trying to do.

    Edited 2 times, last by hyle: Link entfernt ().

  • public class GUI extends JPanel implements Runnable, ActionListener

    and I employ:

    this.setLayout();

    So the compiler will look for the method "setLayout" in all extended and implemented classes until it finds it in Jpanel? I just want to understand how "this" knows what I am trying to do.


    `this` always refers to the current class namespace. If you prefix method calls with this., you're telling the compiler "only search in the current class namespace, if you won't find the member, look into the parent / super class".


    GUI is a JPanel object, so if the compiler wouldn't find `setLayout` in GUI, it would take a look in JPanel. If you have `setLayout` in both GUI and JPanel but you'd like to call the `setLayout` method of the JPanel class, you'd call it with `super.setLayout`.

    “Don’t comment bad code - rewrite it.”

    Brian Kernighan