Object类
1:Object类是所有类的父类,位于java.lang包中
数组也是Object类的子类
Object类的常用方法
toString();
equals();
hashCode();
……
2:Object类在java.lang包下,是所有类的根。任何类的对象,都可以调用Object类中的方法,包括数组对象。
例:
public class A{
public void f(Object obj){ //将Object类作为f方法的参数
}
}
public class Test{
public static void main(){
Example exam=new Example();
int[] array=new int[4];
……//任何数组
exam.f(array);
}
}
3:Object和Object[ ]之间的区别
方法中的形参是Object类型时,任何类型的参数都可以传进去执行。
方法中形参是Object[ ]类型时,只有对象数组可以传入执行。
4:Object类中的常用方法
1)toString 方法
toString方法可以将任何一个对象转换成
字符串返回,返回值的生成算法为:getClass().getName() + '@' + Integer.toHexString(hashCode())。
2)equals方法;
Object类中的equals方法,用来比较两个引用的虚地址。当且仅当两个引用在物理上是同一个对象时,返回值为true,否则将返回false。
任何类可以根据实际需要,覆盖toString及equals方法,实现自定义的逻辑。
equals方法是比较对象的虚地址,但是可以在类中被重写。
如:String类重写了,两个相同值的String对象相比较为 true;
String str=new String(“123”);
String str1=new String(“123”);
System.out.println(str.equals(str1));à打印为true.
具体代码例子:
1 //基类(父类) 2 public class A { 3 //声明属性 4 String name; 5 int num; 6 7 //无参构造方法 8 public A() { 9 10 } 11 12 //有参构造 13 public A(String name, int num) { 14 this.name = name; 15 this.num = num; 16 } 17 18 //父类重写Object类eaquals方法 19 //如果重写的eaquals方法传参不是Object时,就是重新创建了一个A类的eaquals方法 20 //并非对Object类的eaquals方法进行重写 21 22 public boolean equals(Object a) { 23 24 //强制转化为A类的对象,从而可以调用A的属性 25 A b = (A) a; 26 if(b.name.equals(this.name) && b.num == this.num) { 27 return true; 28 }else { 29 return false; 30 } 31 } 32 33 }
1 //B为A的子类 2 public class B extends A{ 3 4 //B类有参构造 5 public B(String name, int num) { 6 this.name = name; 7 this.num = num; 8 } 9 }
1 //C为A的子类 2 public class C extends A{ 3 4 //C类有参构造 5 public C(String name, int num) { 6 this.name = name; 7 this.num = num; 8 } 9 } 10
1 //入口函数 2 public class Main { 3 4 public static void main(String[] args) { 5 // TODO Auto-generated method stub 6 7 A a1 = new A("Kobe",24); 8 9 A a2 = new A("Jordan",23); 10 11 A a3 = new A("Kobe",24); 12 13 B b1 = new B("Kobe",24); 14 15 C c1 = new C("Kobe",24); 16 17 18 System.out.println(a1.equals(a2)); //false 19 System.out.println("-------------"); 20 System.out.println(a1.equals(a3)); //true 21 System.out.println("-------------"); 22 System.out.println(a1.equals(b1)); //true 23 System.out.println("-------------"); 24 System.out.println(a1.equals(c1)); //true 25 } 26 27 }
浙公网安备 33010602011771号