java.lang. 里面的类不用导入包
Object类的成员方法:
public int hashCode();
//就是通过该类在堆上的地址,通过hash算法,算出一个数
public final Class getClass();
//大写 Class 是一种类型;//返回该类的具体类型
|
public String toString();
public boolean equals(Object obj);
|
protected void finalize();
protected Object clone();
|
Student.java | MyObjectDemo.java |
package com.java.objectdemo;
//类不写默认的是继承Object类
public class Student implements Cloneable{ //这种没有任何成员或者抽象方法的接口,被称为 标记接口
String name;
int age;
boolean gender;
public Student(){
}
public boolean equals(Object obj) {
Student stu=(Student) obj;
if(this.name!=null&&stu.name!=null){
if(this.name.equals(stu.name)&&this.age==stu.age&&this.gender==stu.gender )
return true;
}
return false;
}
//protected void finalize() {} //和c++的析构函数两回事
//当垃圾回收器确定不存在对该对象的更多引用时,由对象的垃圾回收器调用此方法。
public Student(String name,int age,boolean gender){
this.name=name;
this.age=age;
this.gender=gender;
}
public Object clone() throws CloneNotSupportedException{
return super.clone();
}
public String toString() {
return "Student [name=" + name + ", age=" + age + ", gender=" + gender + "]";
}
}
|
package com.java.objectdemo;
public class MyObjectDemo {
public static void main(String[] args) {
Student student=new Student();
System.out .println(student.toString()); //对象的字符串表示,建议重写
//默认这里会输出:com.java.objectdemo.Student@15db9742
System.out.println(student); //当我们使用一个对象引用直接输出的时候,系统默认是调用该类的 toString 方法,如果该类没有这个方法就直接调用基类Object的toString方法
//com.java.objectdemo.Student@15db9742
Student student1=new Student("meihao",24,true);
System.out.println( "student1= "+student1);
//student1= com.java.objectdemo.Student@6d06d69c
//这里调用toString方法 返回 getClass().getName() + '@' + Integer.toHexString(hashCode())
System.out.println(student.hashCode()); //366712642
Student student2=new Student();
System.out.println(student2.hashCode()); //2018699554
System.out.println(student2.getClass()); //class com.java.objectdemo.Student
Class oClass; //Class 是一个类,该类是用来代表一个student.class 字节码文件对象
System.out.println("(student1==student2) = "+(student1==student2));
//(student1==student2) = false
//调用equals方法,比较的是地址值是不是一样的;this==object ?
System.out.println("(student1.equals(student2)) = "+(student1.equals(student2))); //(student1.equals(student2)) = false
Student stu1=new Student("qw",20,true);
Student stu2=new Student("qw",20,true);
System.out.println("(stu1==stu2) = "+(stu1==stu2));
//(stu1==stu2) = false
System.out.println("(stu1==stu2) = "+(stu1.equals(stu2)));
//(stu1==stu2) = true
Student st1=new Student("张三",18,true);
Student st2=new Student("张三丰",108,true);
try{
Student st3=(Student)st2.clone(); //创建并返回对象的一个副本;深拷贝,新建一个相同内容对象
Student st4=st2; //浅拷贝,只是多了一个链接
}catch(CloneNotSupportedException e){
e.printStackTrace();
}
}
}
|