java学习日记 Object类

1、Object类是一个公共父类,一个类只要没有明显地继承一个类,则肯定是Object类的子类。

java学习日记 Object类_第1张图片

 

 

2、观察:

class ObjDemo1{

}
public class ObjectDemo1 {
    public static void main(String[] args) {
        ObjDemo1 obj = new ObjDemo1();
        String a = "cnow";
        System.out.println(obj);
        System.out.println(obj.toString());
        System.out.println(a);
    }
}



运行结果:
com.hengqin.test1.ObjDemo1@1b6d3586
com.hengqin.test1.ObjDemo1@1b6d3586
cnow

覆写toString方法:

class ObjDemo1{
    String name;
    int age;
    public ObjDemo1(String name,int age){
        this.name = name;
        this.age = age;
    }
    public String toString(){
        return "姓名:"+this.name+",年龄:"+this.age;
    }
}
public class ObjectDemo1 {
    public static void main(String[] args) {
        ObjDemo1 obj = new ObjDemo1("zacwe",12);
        System.out.println(obj);
        System.out.println(obj.toString());
    }
}

运行结果:

姓名:zacwe,年龄:12
姓名:zacwe,年龄:12

覆写equals()方法:

class ObjDemo1{
    String name;
    int age;
    public ObjDemo1(String name,int age){
        this.name = name;
        this.age = age;
    }
    public String toString(){
        return "姓名:"+this.name+",年龄:"+this.age;
    }
    public boolean equals(Object obj){
        if(this == obj){
            return true;
        }
        if (obj == null){
            return true;
        }
        if (!(obj instanceof ObjDemo1)){
            return false;
        }
        ObjDemo1 objDemo1 = (ObjDemo1)obj;
        if (this.name.equals(objDemo1.name)&&this.age==objDemo1.age){
            return true;
        }
        return false;
    }
}
public class ObjectDemo1 {
    public static void main(String[] args) {
        ObjDemo1 obj = new ObjDemo1("zacwe",12);
        ObjDemo1 obj2 = new ObjDemo1("cwcw",12);
        System.out.println(obj.equals(obj2));
    }
}

运行结果:

false

3、Object可以接收一切引用数据类型

使用Object接收数组

public class ObjectDemo2 {
    public static void main(String[] args) {
        Object obj = new int[] {1,2,3};
        if(obj instanceof int[]){
            int [] data = (int [])obj;
            for (int x:data){
                System.out.println(x);
            }
        }
    }
}

运行结果:

1
2
3

接收接口对象:

interface O{
    public void fun();
}
class Ob implements O{
    public void fun(){
        System.out.println("Hello");
    }
}

public class ObjectDemo2 {
    public static void main(String[] args) {
        O o =new Ob();  //接口对象
        Object obj = o;  //接收接口对象
        Ob ob = (Ob)obj;  //向下转型
        ob.fun();

    }
}

 

你可能感兴趣的:(java学习日记 Object类)