今天突然发现这样一个问题 就是接口中好像也有默认的toString() 方法 象下面的这个例子:
interface test
{}
public class TesttoString implements test
{
private String s;
public TesttoString(String str){
s = str;
}
public String toString(){
return s;
}
public String returnS(){
return s;
}
public static void main(String[] args){
test o = new TesttoString("I don't know!!");
System.out.println(o);
System.out.println(o.toString());
System.out.println(((TesttoString)o).returnS());
//System.out.println(o.returnS()); }
}
我没有在接口中定义 toString() 方法 但是实现他的类 TesttoString 却可以向上转型付给 test 如果是 子类继承自父类的话 这个就好理解,类都是 Object 的子孙, 但是我好像没有在那本书上看见说接口 有这个功能的呀 ! 象o.returnS()这个调用会报错的,这个也好理解 但就是toString() 呀 !!!!
interface test
{}
public class TesttoString implements test
{
private String s;
public TesttoString(String str){
s = str;
}
public String toString(){
return s;
}
public String returnS(){
return s;
}
public static void main(String[] args){
test o = new TesttoString("I don't know!!");
System.out.println(o);
System.out.println(o.toString());
System.out.println(((TesttoString)o).returnS());
//System.out.println(o.returnS()); }
}
我没有在接口中定义 toString() 方法 但是实现他的类 TesttoString 却可以向上转型付给 test 如果是 子类继承自父类的话 这个就好理解,类都是 Object 的子孙, 但是我好像没有在那本书上看见说接口 有这个功能的呀 ! 象o.returnS()这个调用会报错的,这个也好理解 但就是toString() 呀 !!!!
并不是“所有类都继承了Object类,所以所有对象都拥有它的方法”
而是 “所有的对象都默认拥用Object类的方法,刚好看起来符合继承这条规则”呵呵,大家一起研究研究
declares a public abstract member method m with signature s, return type r,
and throws clause t corresponding to each public instance method m with
signature s, return type r, and throws clause t declared in Object, unless a
method with the same signature, same return type, and a compatible throws
clause is explicitly declared by the interface. It is a compile-time error if the
interface explicitly declares such a method m in the case where m is declared to
be final in Object.
接口隐含定义了一套与Object类中的方法签名完全相同的方法;如果接口定义一个在Object中定义为final的会编译出错。
interface test
{}
public class TesttoString implements test
{
private String s;
private int i;
public TesttoString(String str,int j){
s = str;
i = j;
}
public String toString(){
return i+" : "+ s;
}
public String returnS(){
return s;
}
public int hashCode(){
return i;
}
public static void main(String[] args){
test o = new TesttoString("I don't know!!",1);
System.out.println(o);
System.out.println(o.toString());
System.out.println(((TesttoString)o).returnS());
System.out.println(o.hashCode());
//System.out.println(o.returnS()); }
}结果可以输出 哈希玛 1 的
>>而不是“类”,而接口似乎在理论上是不可以继承Object类的EmptyInterface e = new SomeImplemention();
String s = e.toString();//e既然是接口的实例,证明它是对象。能继承接口的,必然是Object。编译器和你我都知道这一点。对不起。
>>接口不能有实例的,接口只是提供了一系列的方法接口,且都是空的,以供多肽机制的
接口当然可以有实例(instance,名词),抽象类也可以有实例,只不过是不能直接实例化而已。实现了一个接口的对象就是这个接口的一个实例。