java中的例項判斷---obj instanceof Person
阿新 • • 發佈:2022-04-06
java中的例項判斷
package com.msb02; public class Person { String name; int age; double hight; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getHight() { return hight; } public void setHight(double hight) { this.hight = hight; } public Person() { } public Person(String name, int age, double hight) { this.name = name; this.age = age; this.hight = hight; } /* @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + ", hight=" + hight + '}'; return (this == obj); }*/ public boolean equals(Object obj) { //判斷obj類例項是否屬於Person的子類 if( obj instanceof Person) {//把person轉成obj型 Person other = (Person)obj; if(this.getAge()==other.getAge()&&this.getName()==other.getName()&&this.getHight()==other.getHight()){ return true; } } return false; } }
package com.msb02;
public class Cat {
}
package com.msb02; public class Test { public static void main(String[] args) { Person person = new Person("麗麗",24,165.3); Person per =new Person("麗麗",24,165.3); Cat cat = new Cat(); boolean a = person.equals(cat);//判斷cat是否和person相同 System.out.println(a); } }