getClass()方法
调用时返回对象执行时的Class实例,然后使用次实例调用getName()方法可以取得类的名称,语法如下:
getName.getname();
toString()方法
调用时将对象返回为字符串形式,它会返回一个String实例
//让学生自我介绍
public class Student {
String name;
int age;
public Student(String name,int age){
this.name = name;
this.age = age;
}
public String toString(){
return "我叫" + name + ",今年" + age + "岁。";
}
public static void main(String[] args) {
Student s1 = new Student("张三",16);
System.out.println(s1);
Student s2 = new Student("李四",16);
System.out.println(s2);
}
}
equals()方法
//根据身份证号判断是否为同一人
public class People {
int id;
String name;
public People(int id,String name){
this.name = name;
this.id = id;
}
public boolean equals(Object obj){
if(this == obj)
return true;
if(this == null)
return false;
if(getClass() != obj.getClass())
return false;
People other = (People)obj;
if(id != other.id)
return false;
return true;
}
public String toString(){
return name;
}
public static void main(String[] args) {
People p1 = new People(220,"tom");
People p2 = new People(220,"汤姆");
People p3 = new People(330,"张三");
Object o = new Object();
System.out.println(p1 + "与" + p2 + "是否为同一人?");
System.out.println("equals()方法的结果:" + p1.equals(p2));
System.out.println("==运算符的结果:" + (p1 == p2));
System.out.println();
System.out.println(p1 + "与" + p3 + "是否为同一人?");
System.out.println(p1.equals(p3));
System.out.println(p1 + "与" + o + "是否为同一人?");
System.out.println(p1.equals(o));
}
}