KnowledgeBoat Logo
|

Computer Applications

What is the use of the keyword this?

Java Constructors

6 Likes

Answer

Within a constructor or a method, this is a reference to the current object — the object whose constructor or method is being invoked. The keyword this stores the address of the currently-calling object.

For example, the below program makes use of the this keyword to resolve the conflict between method parameters and instance variables.

class  Area
{
    int  length,  breadth;

    public Area(int length, int breadth) {
        this.length = length;
        this.breadth =  breadth;
    }
    
    public void Display() {
    int	area = length * breadth;
    System.out.println("Area is " + area);
    }

    public static void main(String args[J) {
    Area area = new Area(2, 3);
    area.Display();
    }
}

Answered By

3 Likes


Related Questions