+ 5
[SOLVED] Does 'this' keyword work in a constructor (JAVA) ?
I just tried like color = this.color in a constructor and it gave a null output. But when i changed it into color = c after changing the variable, it worked.
8 Respuestas
+ 8
this keyword refers to current context (class), used to refers current class instance field, method and also constructor.
From this simple demo code, you can understand how it's works.
public class Program
{
public static String string="current class field";
public Program(String string){
System.out.println(this.string);
System.out.println(string);
}
public static void main(String[] args) {
Program p=new Program("Parameter for constructor");
}
}
+ 3
class myClass{
String color; //first_color
myClass(String color /*second_color */){
this.color = color;
/*first_color = second_color */
}
}
//see correct method
//same variable name with different memory allocation
+ 3
Yeah bro
this means the current object.
Accessing the methods and attributes of the of the current object using this keyword
+ 3
Kelvin Paul this keyword basically means that you are referring to the object you are using to access the method.
+ 3
Yeah bro☺pNK.
I already mentioned about that in my second answer. please see that ☺
+ 1
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
String movie = read.nextLine();
int row = read.nextInt();
int seat = read.nextInt();
Ticket ticket = new Ticket(movie, row, seat);
System.out.println("Movie: " + ticket.getMovie());
System.out.println("Row: " + ticket.getRow());
System.out.println("Seat: " + ticket.getSeat());
}
}
class Ticket {
private String movie;
private int row;
private int seat;
//complete the constructor
public Ticket(String m, int r, int s) {
movie = m;
row = r;
seat = s;
}
public String getMovie() {
return movie;
}
public int getRow() {
return row;
}
public int getSeat() {
return seat;
}
}
+ 1
Kelvin Paul this is the code bit i tried and it worked^
But i wanted to know why in the Constructor when i replace String m variable name with 'movie' and under under constructor, replace movie = m with movie = this.movie , it gives me null
+ 1
Kelvin Paul ok so when we use 'this' keyword, it refers to the variable in the class and not the one in method?