//强制类型转换与instanceof
class Stu
{
private String name;
private int age;
public Stu(String name,int age)
{
this.name = name;
this.age = age;
}
}
class Student
{
private String name;
private int age;
public Student(String name,int age)
{
this.name = name;
this.age = age;
}
public boolean equals(Object obj) //重写Object类中的equals()方法,如果不重写则输出结果都为false
{
if(obj instanceof Student) //判断传入的参数是否是Student类型
{
Student st = (Student)obj; //强制类型转换 Object --> Student
if(this.name == st.name && this.age == st.age)
return true;
else
return false;
}
else
return false;
}
public static void main(String[] args)
{
Student st1 = new Student("zhangsan",20);
Student st2 = new Student("zhangsan",20);
Stu st3 = new Stu("zhangsan",20);
if(st1.equals(st2)) //Student类对象调用equals()时系统进行了隐式转换,将Student --> Object
System.out.println("equals"); //打印结果为equals
else
System.out.println("no equals");
if(st1.equals(st3))
System.out.println("equals");
else
System.out.println("no equals"); //打印结果为no equals
/*String str1 = "abc";
String str2 = "abc";
if(str1.equals(str2)) //equals()方法如果用于此处不用进行强制类型的转换
System.out.println("eqauls");
else
System.out.println("no eqauls");*/
}
}
class Stu
{
private String name;
private int age;
public Stu(String name,int age)
{
this.name = name;
this.age = age;
}
}
class Student
{
private String name;
private int age;
public Student(String name,int age)
{
this.name = name;
this.age = age;
}
public boolean equals(Object obj) //重写Object类中的equals()方法,如果不重写则输出结果都为false
{
if(obj instanceof Student) //判断传入的参数是否是Student类型
{
Student st = (Student)obj; //强制类型转换 Object --> Student
if(this.name == st.name && this.age == st.age)
return true;
else
return false;
}
else
return false;
}
public static void main(String[] args)
{
Student st1 = new Student("zhangsan",20);
Student st2 = new Student("zhangsan",20);
Stu st3 = new Stu("zhangsan",20);
if(st1.equals(st2)) //Student类对象调用equals()时系统进行了隐式转换,将Student --> Object
System.out.println("equals"); //打印结果为equals
else
System.out.println("no equals");
if(st1.equals(st3))
System.out.println("equals");
else
System.out.println("no equals"); //打印结果为no equals
/*String str1 = "abc";
String str2 = "abc";
if(str1.equals(str2)) //equals()方法如果用于此处不用进行强制类型的转换
System.out.println("eqauls");
else
System.out.println("no eqauls");*/
}
}