首页 > 代码库 > 黑马程序员-面向对象-Object类

黑马程序员-面向对象-Object类

---------------------- <a href=http://www.mamicode.com/"http://edu.csdn.net"target="blank">ASP.Net+Unity开发、.Net培训、期待与您交流! ---------------------->
	public void setName(String name)
	{this.name = name;}
	public String getName()
	{return name;}
	public void setAge(int age)
	{this.age = age;}
	public int getAge()
	{return age;}
	public boolean equals(Object obj)
	{
		if(this == obj)
		{return true;}
		if(obj instanceof Person)
		{
		Person p1 = (Person)obj;
		return (this.getName()== p1.getName())&& (this.getAge()== p1.getAge());			}
		return false;
	}
}
class PersonDemo
{
	public static void main(String[] args)
	{   Person p1 = new Person("张三",25);
		Person p2 = new Person("张三",25);
        System.out.println( p1.equals(p2));
	}
}
 


二.Object类中的toString方法
 public String toString()
 返回该对象的字符串表示。通常,toString 方法会返回一个
 “以文本方式表示”此对象的字符串。结果应是一个简明但易
 于读懂的信息表达式。建议所有子类都重写此方法。 

class Person
{
	private String name;
	private int age;
	public Person(){}
	public Person(String name,int age)
	{this.name = name; this.age = age;}
	public void setName(String name)
	{this.name = name;}
	public String getName()
	{return name;}
	public void setAge(int age)
	{this.age = age;}
	public int getAge()
	{return age;}
	public String toString()
	{
      return name;
    }
}
class Day02
{
	public static void main(String[] args)
	{
		Person p1 = new Person("张三",25);
		Person p2 = new Person("张三",24);
        System.out.println( p1.toString());//
		//没有toString()方法输出的是Person@1db9742
		//返回的是一个字符串,由“@”和此对象哈希码的
		//无符号十六进制表示组成,比较难懂,建议定义toString()
		//方法,复写父类Object的toString方法,自定义字符串表现形式
        //有了toString方法后,覆写了object类中的toString方法
		//自定义了返回的字符串表现形式,输出结果就是:张三
	}
}




三.Object类中的getClass
返回的的是当前对象所属类的字节码文件对象(Class)

一个字节码文件对象可以对应好几个对象
所以 System.out.println(cls1 == cls2);//true

而Class类中有getName()方法,getField()方法,getMethod()方法等等
               
public final Class<?> getClass()
class Person
{
	private String name;
	private int age;
	public Person(){}
	public Person(String name,int age)
	{this.name = name; this.age = age;}
	public void setName(String name)
	{this.name = name;}
	public String getName()
	{return name;}
	public void setAge(int age)
	{this.age = age;}
	public int getAge()
	{return age;}
}
class Day02
{
	public static void main(String[] args)
	{
		Person p1 = new Person("zhangsan",24);
		Person p2 = new Person("lisi",25);
  Class cls1 = p1.getClass();
		Class cls2 = p2.getClass();
        System.out.println(cls1);//class Person
		System.out.println(cls2);//class Person
		System.out.println(cls1 == cls2);//true
        System.out.println(cls1.getName());//Person
       }
}
---------------------- <a href=http://www.mamicode.com/"http://edu.csdn.net"target="blank">ASP.Net+Unity开发、.Net培训、期待与您交流! ---------------------->