1、equals方法的小问题
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");
}
}
}
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方法了呢,这个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;
}
}
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;
}
} 对于你的疑问,需要先从Object这个类说起。Obeject类是所有没有显式继承其他类的父类。也就是说类 Object 是类层次结构的根类。每个类都使用 Object 作为超类。这个根类中有equals方法。
一、任何继承Obeject类的子类,要么直接使用Object类中的方法,直接使用的话,就是直接使用Object类中的equas的功能,这个功能就是指示其他某个对象是否与此对象“相等”,她比较的是地址值。要么覆写其中的方法