本帖最后由 李洪因 于 2013-3-15 21:40 编辑
- public class Student {
-
- public static void main(String[] args)
- {
- Scanner sc = new Scanner(System.in);
- System.out.println("请输入用户名:");
- String username = sc.nextLine();
- System.out.println("请输入密码:");
- String password = sc.nextLine();
- if (username.equals("admin") && password.equals("admin")) {
- System.out.println("true");}
- else
- {
- System.out.println("false");
- }
-
- }
-
- }
复制代码 为什么上面的equals方法没有复写但是正确呢?
而下面的代码切要复写了equals方法了呢?- public class Student {
- private String name;
- private int age;
- public Student(String name,int age)
- {
- this.name=name;
- this.age=age;
- }
- public static void main(String[] args)
- {
- Student st1 = new Student("zhang",20);
- Student st2 = new Student("zhang",20);
- if(st1.equals(st2))
- System.out.print("相等");
- else
- System.out.print("不相等");
- }
- public boolean equals(Object obj){
-
-
-
- if(obj==null) return false;
- else
- {
- if(obj instanceof Student){
- Student c=(Student)obj;//强制转换
- if(c.name==this.name && c.age==this.age ){
- return true;
- }
- }
- }
- return false;
-
- }
-
- }
复制代码 我想知道这个equals方法什么时候复写呢?请教各位大侠。。。 |