创建Object类型实例
java任何引用类型对象都可以赋值给Object类型变量
package com.szb.interfaces;
public interface BaseInterface {//创建接口
Object superMethod(Object obj);
}
package com.szb.interfaces.imp;
import com.szb.interfaces.BaseInterface;
public class Imp implements BaseInterface {
@Override
public Object superMethod(Object obj) {//实现接口
int [] ints = (int [])obj;
return ints.length > 1?ints[0]+ints[1]:0;
}
}
package com.szb.interfaces.imp;
import com.szb.interfaces.BaseInterface;
public class Imp2 implements BaseInterface {
@Override
public Object superMethod(Object obj) {
String str = (String)obj;
return str.length()>=6 && str.length()<=16?true:false;
}
}
package com.szb.test;
import com.szb.interfaces.BaseInterface;
import com.szb.interfaces.imp.Imp;
import com.szb.interfaces.imp.Imp2;
public class Test {
public static void main(String[] args) {
BaseInterface b1 = new Imp();//回调接口
BaseInterface b2 = new Imp2();
int []ints1 = {56,15};
int sum = (int)b1.superMethod(ints1);
System.out.println(sum);
boolean bool = (boolean)b2.superMethod("sdfhjsakljf");
System.out.println(bool);
}
}
toString方法
toString方法返回Object对象的字符串表示形式
此方法可以在任何类中进行重写,重写后将得到一个新的字符串返回形式
重写Object中的toString方法
package entity;
public class Users {
String name;
public String toString() {
String begin = "{";
String end ="}";
begin+="\"";
begin+="name";
begin+="\"";
begin+=" = ";
begin+=this.name;
begin+=end;
return begin;
}
public Users(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Users() {
super();
}
}
package test;
import entity.Users;
public class Test {
public static void main(String[] args) {
Users users = new Users("帕瓦罗蒂");
System.out.println(users.toString());
}
}
Object类中的toString方法
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
equals方法
equals用来判断给定的对象是否与当前对象相等
equals方法可以被子类重写,从而改变具体算法
package com.szb.entity;
public class Employee {
private String id;
private String name;
public Employee(String id, String name) {
super();
this.id = id;
this.name = name;
}
public Employee() {
super();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object obj) {
Employee emp = (Employee)obj;
return this.getId().equals(emp.getId())?true:false;
}
}
package com.szb.test;
import com.szb.entity.Employee;
public class Test2 {
public static void main(String[] args) {
Employee emp0 =new Employee("emp009","令狐冲");
Employee emp2 =new Employee("emp009","任盈盈");
boolean bool = emp0.equals(emp2);
System.out.println(bool?"2个对象的ID值是相同的":"两个对象的ID值是不同的");
}
}