黑马程序员-----object 类和包装类

/**
* @author Administrator
*
* @description Object类学习测试类
* @history
*/
public class ObjectTestDemo {
/**
*@description
*@param args
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws ClassNotFoundException {
// Object类学习测试代码
// 1、 toString方法
// 2、 equals和hashCode方法
// 3、 getClass方法
ObjectTestDemo otd = new ObjectTestDemo();
System.out.println(otd);
System.out.println(otd.toString());// 现实调用toString方法
/*
* Object类中toString方法
* public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
* Object类中equal方法
* public boolean equals(Object obj) {
return (this == obj);
}*/
// 定义昵称和年龄属性,如果昵称和年龄相同则equal方法返回true
ObjectTestDemo otd1 = new ObjectTestDemo();
otd1.nickname = "eclipse";
otd1.age = 20;
ObjectTestDemo otd2 = new ObjectTestDemo();

otd2.nickname = "eclipse";
otd2.age = 20;
System.out.println(otd1==otd2); // false
System.out.println(otd1.equals(otd2)); // 如果不覆写的话返回的一直是false
// hashCode方法和equals方法的关系,没有绝对的关系
// 具体参看源代码的注释说明,在实际用中尽量同时覆写这两个方法,保持一致性
// public final native Class<?> getClass();
// getClass方法是一个本地方法,调用底层代码,返回当前对象对应的一个类对象实例
// 类对象实例,理解为内存中对应的那份字节码对象, java反射内容初步学习
// 通过字节码对象构造出一个个的对象实例
Class claz = otd.getClass();
Class claz1 = ObjectTestDemo.class;
Class claz2 = Class.forName("ObjectTestDemo"); // 类的完整路径
System.out.println(otd.getClass()); // class ObjectTestDemo
// VM内存中只会产生一份字节码对象
System.out.println(claz == claz1); // true
}
// 方法模拟,添加两个属性昵称和年龄
private String nickname;
private int age;
// 注意参数类型不要写成了ObjectTestDemo
public boolean equals(Object obj) {
ObjectTestDemo otd = (ObjectTestDemo) obj; // 向上转型,强制转换
if (this == otd) {
return true;
}
if (otd instanceof ObjectTestDemo) {
if (this.nickname.equals(otd.nickname) && this.age == otd.age) {
return true;
}
}
return false;
}
public String toString(){
return "helloworld"; //覆写toString方法,返回helloworld
}
}

posted on 2015-10-11 09:38  yulai2015  阅读(259)  评论(0编辑  收藏  举报

导航