Java this keyword tutorial


  • this keyword can use to refer the current class constructor.
    public class Human {
        private String name;
        private int age;
    
        public Human() {
            System.out.println("This is default constructor");
        }
    
        public Human(String name, int age) {
    
            this();
    
            this.name = name;
            this.age = age;
        }
    }
    this();

    Calling a constructor withng a constructor called constructor chaining. Calling a constructor must be the first thing in the constructor, otherwise it will give you this error

    error: call to super must be first statement in constructor


  • this keyword can use to refer the current class instance variables.
        public Human(String name, int age) {
            this.name = name;
            this.age = age;
        }

    In this sample, this keyword indicates that both name and age variables belong to current class instant variables. So the method arguments will be assigned to the current class instant variables. If we are not going to use this keyword here, then the meaning will be method arguments values will be assigned to the same method arguments.



  • this can use to pass as an argument in the constructor call.
    public class Human {
        private String name;
        private int age;
        private House house;
    
        public Human(String name, int age) {
    
            house = new House(this);
    
            this.name = name;
            this.age = age;
        }
    }
    
    public class House {
        private Human human;
        public House (Human human) {
            this.human = human;
        }
    }


  • this can use to pass as an argument in the method call.
    public class Human {
        private String name;
        private int age;
    
        public Human(String name, int age) {
    
            this.name = name;
            this.age = age;
        }
    
        public void mySelf() {
            speak(this);
        }
    
        private void speak(Human human) {
            System.out.println("My name is " + human.name + " and my age is " + human.age);
        }
    }

<< Java keywords and syntax      Java super keyword >>