《java入门第一季》之类(Object类)

package cn.itcast_01;

/*
* Object:类 Object 是类层次结构的根类。每个类都使用 Object 作为超类。
* 每个类都直接或者间接的继承自Object类。
*
* Object类的方法:
* public int hashCode():返回该对象的哈希码值。一般不同的对象具有不同的哈希码值。
* 注意:哈希值是根据哈希算法计算出来的一个值,这个值和地址值有关,但是不是实际地址值。
* 你可以理解为地址值。
*
* public final Class getClass():返回此 Object 的运行时类,此时运行的是哪个类,调用getName()方法后会返回该类的全名。
* Class类的方法:
* public String getName():以 String 的形式返回此 Class 对象所表示的实体
* 返回:
此对象所表示的类或接口名。 */
public class StudentTest {
public static void main(String[] args) {
Student s1 = new Student();
System.out.println(s1.hashCode()); // 11299397
Student s2 = new Student();
System.out.println(s2.hashCode());// 24446859
Student s3 = s1;
System.out.println(s3.hashCode()); // 11299397
System.out.println("-----------"); Student s = new Student();
Class c = s.getClass();
String str = c.getName();
System.out.println(str); // cn.itcast_01.Student //链式编程
String str2 = s.getClass().getName();
System.out.println(str2);
}
}

Object类的方法:public String toString():返回该对象的字符串表示。

//Object类的 toString()方法的值等价于它      getClass().getName() + '@' + Integer.toHexString(hashCode())

但是自定义类的时候一半会重写tistring方法,不然输出默认调用object类中的tostring。如何重写?自动生成即可。

注意:

 * 直接输出一个对象的名称,其实就是调用该对象的toString()方法。通过这里可以看出类是否重写过Object类的tostring方法

 * 如果结果是一个地址的形式,就说明没有重写Tostring方法。

/*

 *方法: public boolean equals(Object obj):指示其他某个对象是否与此对象“相等”。 

 * 这个方法,默认情况下比较的是地址值。比较地址值一般来说意义不大,所以要重写该方法。

 * 怎么重写呢?

 * 一般都是用来比较对象的成员变量值是否相同。

 * 其实还是自动生成。

 * 

 * 看源码:

 * public boolean equals(Object obj) {

 * //this - s1//谁先调用这个方法this就代表谁

 * //obj - s2

 *       return (this == obj);

 *   }

 * 

 * ==:

 * 基本类型:比较的就是值是否相同

 * 引用类型:比较的就是地址值是否相同

 * equals:

 * 引用类型:默认情况下,比较的是地址值。

 * 不过,我们可以根据情况自己重写该方法。一般重写都是自动生成,比较对象的成员变量值是否相同

 */

代码演示:

public class StudentDemo {
public static void main(String[] args) {
Student s1 = new Student("林青霞", 27);
Student s2 = new Student("林青霞", 27);
System.out.println(s1 == s2); // false
Student s3 = s1;
System.out.println(s1 == s3);// true
System.out.println("---------------"); System.out.println(s1.equals(s2)); // obj = s2; //true
System.out.println(s1.equals(s1)); // true
System.out.println(s1.equals(s3)); // true
Student s4 = new Student("风清扬",30);
System.out.println(s1.equals(s4)); //false Demo d = new Demo();
System.out.println(s1.equals(d)); //ClassCastException }
} class Demo {}

注意:在Student类中是重写了equals()方法的。重写的代码如下:

	Student类中重写equals方法。

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
上一篇:jQuery mouse and lunbo


下一篇:[C#详解] (1) 自动属性、初始化器、扩展方法