Java Question that is kind of obvious...
Go to solution
Solved by Tazman192,
Say for example you have a class, and you instantiate it (i.e creating an object - a class is a blueprint for an object essentially), you can use the keyword "this" to refer to fields within the object that you just created.
So a quick example may be
public class Car { public int numberOfDoors = 5; public int maxSpeed = 70; //constructor public Car(int a, int b) { numberOfDoors = a; maxSpeed = b; }}You can use the constructor to create an object of type car. You may have a 3 door car, so you'd simply create an object using the constructor.
Saying that, a neater way to write the above code would be:
public class Car { public int numberOfDoors = 5; public int maxSpeed = 70; //constructor public Car(int numberOfDoors, int maxSpeed) { this.numberOfDoors = numberOfDoors; this.maxSpeed = maxSpeed; }}Notice the use of "this". I am referring directly to the fields within the new object you create using the character. We can use the first method, but the second method is easier to follow, and disallows any ambiguity from instance and local variables (including parameters).
tl;dr
"this" keyword can be used in the following ways:
- To get reference of an object through which that method is called within it (instance method - i.e the example above)
- To avoid fields shadowed by a method or constructor parameter (using the same names for local and instance fields, second piece of code demonstrates this)
- To invoke a constructor of same class.
Note we can't use the "this" keyword with static methods
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now