日期:2014-05-20 浏览次数:20722 次
class Person { String name; int age; Person(String name, int age) { this.name=name; this.age=age; } String toPrint(Object obj) { if( !(obj instanceof Person) )//如果obj不是Person的实例,不同的对象,就没有比较的意义 { return "无效比较!"; } Person p = (Person)obj;//而且当obj不是Person的实例,在进行类型转换时,会抛出异常 return (this.age > p.age)? this.name:p.name; } } public class Main { public static void main(String [] args) { Person p1 = new Person("Allen",20); Person p2 = new Person("Jack",30); System.out.println( p1.toPrint(p2) ); System.out.println( p1.toPrint(new String("hello")) ); } }