+ 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.

15th Nov 2020, 10:02 AM
Thashreef Mohammed
Thashreef Mohammed - avatar
8 ответов
+ 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"); } }
15th Nov 2020, 10:23 AM
0_O-[Mägár_Sám_Äkà_Nüllpøïntêr_Èxëcéptïön]~~
0_O-[Mägár_Sám_Äkà_Nüllpøïntêr_Èxëcéptïön]~~ - avatar
+ 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
15th Nov 2020, 10:21 AM
Kelvin Paul
Kelvin Paul - avatar
+ 3
Yeah bro this means the current object. Accessing the methods and attributes of the of the current object using this keyword
15th Nov 2020, 10:25 AM
Kelvin Paul
Kelvin Paul - avatar
+ 3
Kelvin Paul this keyword basically means that you are referring to the object you are using to access the method.
15th Nov 2020, 12:13 PM
pNK
pNK - avatar
+ 3
Yeah bro☺pNK. I already mentioned about that in my second answer. please see that ☺
15th Nov 2020, 12:16 PM
Kelvin Paul
Kelvin Paul - avatar
+ 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; } }
15th Nov 2020, 10:15 AM
Thashreef Mohammed
Thashreef Mohammed - avatar
+ 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
15th Nov 2020, 10:18 AM
Thashreef Mohammed
Thashreef Mohammed - avatar
+ 1
Kelvin Paul ok so when we use 'this' keyword, it refers to the variable in the class and not the one in method?
15th Nov 2020, 10:22 AM
Thashreef Mohammed
Thashreef Mohammed - avatar