Object类及常用方法(getClass()、hashCode()、toString())
程序员文章站
2022-04-16 09:52:49
...
1. Object类
package com.fy.t2;
public class TestObject {
public static void main(String[] args) {
method(new Student());
System.out.println();
}
public static void method(Object obj) {
}
public static void goHome(Object obj) {
}
public static Object buyVehicle(int n) {
return null;
}
}
class Dog {}
class Cat {}
class Student {}
2. getClass()方法
package com.fy.t2;
/**
* getClass()方法:返回引用中存储的实际对象类型
* @author 方圆
*应用:
*通常用于判断两个引用中实际存储对象类型是否一致
*/
public class TestGetClass {
public static void main(String[] args) {
Student1 s = new Student1();
System.out.println(s.getClass());
Object o = new Object();
System.out.println(o.getClass());
Animal a = new Dog1();
System.out.println(a.getClass());
Animal a1 = new Dog1();
Animal a2 = new Cat1();
Animal a3 = new Bird();
Animal a4 = new Cat1();
/*
if(a1 instanceof Cat) {
if(a2 instanceof Cat) {
}
}
*/
if(a1.getClass() == a2.getClass()) {
System.out.println("sametype");
}else {
System.out.println("noSame");
}
}
}
class Student1{}
class Animal{}
class Dog1 extends Animal{}
class Cat1 extends Animal{}
class Bird extends Animal{}
3. hashCode()方法
package com.fy.t2;
/**
* hashCode()方法
*
* 返回该对象的十进制的哈希值
* 哈希算法根据对象的地址或者是字符串或数字计算出来的int类型的数值
* 哈希码并不唯一,可以保证相同对象返回相同哈希码,尽量保证不同对象返回不同哈希码
* @author 方圆
*
*/
/**
* toString()方法
*
* @author 方圆
* 源码:拼接
* public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
*
*/
public class TestHashCode {
public static void main(String[] args) {
for(int i = 0; i < 5; i++) {
Object o = new Object();
System.out.println(o.hashCode() + "\t" + o);
System.out.println(o.hashCode() + "\t" + o.toString());
System.out.println(o.hashCode() + "\t" + Integer.toHexString(o.hashCode()));
}
}
}
class Teacher2{
public String toString() {
return null;
}
}
toString()方法
上一篇: java_小练习——统计一个字符串中各个数字出现次数
下一篇: 【性能调优】堆外内存溢出
推荐阅读