Search This Blog

Tuesday, December 25, 2012

"this" keyword java examples - with and without "this"


Understanding the problem without "this" keyword

class Student{
    int id;
    String name;

    Student(int id, String name){
        id = id;
        name = name;
    }

    void display(){
        System.out.println(id+" "+name);
    }

    public static void main(String args[]){
        Student s1 = new Student(101, "Jahn");
        Student s2 = new Student(102, "Robin");
        s1.display(); //0 null
        s2.display(); //0 null
    }
}
Solution of the above problem using "this" keyword

class Student{
    int id;
    String name;

    Student(int id, String name){
        this.id = id;                    //try with "this" keyword
        this.name = name;                //try with "this" keyword
    }

    void display(){
        System.out.println(id+" "+name);
    }

    public static void main(String args[]){
        Student s1 = new Student(101, "Jahn");
        Student s2 = new Student(102, "Robin");
        s1.display();         s2.display();    }
}

Source: http://www.javatpoint.com/this-keyword
Check this link. It has all 6 types of examples using "this" keyword

1 comment: