Почему мой вывод ложен в большинстве программ на java?
<code begins> public class Welcome{ public static void main(String args[]){ Hello h1=new Hello("Hello"); Hello h2=new Hello("Hello"); System.out.println(h1.equals("Hello")); } } class Hello{ String name; Hello(String name){ this.name=name; } public boolean equals(Hello h){ return this.name==h.name; } } </code ends> Output: false I apologize for my mistakes. After looking at comments from some members, I found out that I typed the code wrong. I am sorry. I have corrected them. Hi.'Hello' is a class and h1 and h2 are reference variables of class 'Hello'. I call the constructor of 'Hello' class by using "Hello" String arguments, which invokes the respective constructor. I have two questions. 1> 'this' keyword, how does it know that it is referring to object h1 or h2 that is compared. Is it because I used h1.equals? A little explanation of how 'this' keyword works would be helpful. 2> Even though I pass a String "Hello" in equals and compare, I get the output as false. How is this possible? Next, I would like to modify the above program a little bit as: <code begins> public class Welcome{ public static void main(String args[]){ String s1=new String("Hello"); String s2=new String("Hello"); Hello h1=new Hello(s1); Hello h2=new Hello(s2); System.out.println(h1.equals(h2)); } } class Hello{ String name; Hello(String name){ this.name=name; } public boolean equals(Hello h){ return this.name==h.name; } } </code ends> Output: false Here, how is it false again? Is the reason same as for the above program? How is output changing when I replace program 2 with the overridden 'equals' method with .equals instead of == as: <code begins> public boolean equals(Hello h){ return this.name.equals(h.name); } </code ends> Output: true What is wrong if I pass Object class reference as this in Program 2: <code begins> public boolean equals(Object h){ return this.name.equals.(h.name); } </code ends> Output: Compilation Error
Что я уже пробовал:
Я пробовал выполнять вышеприведенные коды.