berione
berione

Reputation: 122

Using "this" inside of a method (not for calling a method or constructor or variable)

I tried to change the capacity of a vector without the use of the constructor parameter in the Vector class. So I created a MyVector class and extended it from Vector. Everything is working in this code but I couldn't understand using "this" in the setCapacityIncrement(int capacityIncrement) method.

public class App {
    public static void main(String [] args)
    {
        MyVector<Integer> v = new MyVector<>(4);

        System.out.printf("Capacity=%d%n", v.capacity());

        for (int i = 0; i < 5; ++i)
            v.add(i);

        System.out.printf("Capacity=%d%n", v.capacity());

        v.setCapacityIncrement(10);

        for (int i = 0; i < 5; ++i)
            v.add(i);

        System.out.printf("Capacity=%d%n", v.capacity());
    }
}

MyVector class :

class MyVector<T> extends Vector<T> {
    public MyVector()
    {
        super();
    }

    public MyVector(int capacity)
    {
        super(capacity);
    }

    public MyVector(Collection<? extends T> coll)
    {
        super(coll);        
    }

    public MyVector(int capacity, int capacityIncrement)
    {
        super(capacity, capacityIncrement);
    }

    public void setCapacityIncrement(int capacityIncrement)
    {
        this.capacityIncrement = capacityIncrement;
    }
}  

Upvotes: 0

Views: 52

Answers (2)

George Mulligan
George Mulligan

Reputation: 11903

You need this.capacityIncrement because the field is shadowed by the parameter capacityIncrement since they have the same name.

If you did capacityIncrement = capacityIncrement; you would be assigning the same value to your capacityIncrement parameter which would have no effect.

If they did not have the same name then this would not be required as in below:

public void setCapacityIncrement(int increment)
{
    capacityIncrement = increment;
}

Based on your edit it would also be a bad idea to have a capacityIncrement field in your MyVector class because there is already a protected variable with the same name in the parent Vector.

That would cause the Vector capacityIncrement field to be shadowed by your own.

Upvotes: 2

Mo1989
Mo1989

Reputation: 2494

when you use "this" you are referring to the object of the class. Therefore, this.capacityIncrement refers to the variable capacityIncrement in the object of the vector class tat its called from. Notice that the parameter passed into the method is also called capacityIncrement. So if you just wrote, capacityIncrement = capacityIncrement without the "this." the compiler would just assume you're referring to the local variable i.e. the parameter.

The variable capacityIncrement is a protected variable in the vector class. this means that only the vector class or classes extending the vector class can access it directly.

Upvotes: 0

Related Questions