关于接口的问题求指教?
程序代码:
package test;
interface ISport {
void run();
}
class Athelete implements ISport {
public void run() {
System.out.println("三级跳");
}
}
class Students implements ISport {
public void run() {
System.out.println("我随便跑跑");
}
}
class CollegeStudent extends Students {
public void study() {
System.out.println("好好学习,天天向上");
}
}
public class AnyTest {
public static void main(String[] args) {
ISport i = new Athelete();
i.run();
i = new Students();
i.run();
i = new CollegeStudent();
i.run();
i.study();// 为山么i无法引用到设个方法?i=new CollegeStudent();
CollegeStudent name = new CollegeStudent();
name.study();
}
}
interface ISport {
void run();
}
class Athelete implements ISport {
public void run() {
System.out.println("三级跳");
}
}
class Students implements ISport {
public void run() {
System.out.println("我随便跑跑");
}
}
class CollegeStudent extends Students {
public void study() {
System.out.println("好好学习,天天向上");
}
}
public class AnyTest {
public static void main(String[] args) {
ISport i = new Athelete();
i.run();
i = new Students();
i.run();
i = new CollegeStudent();
i.run();
i.study();// 为山么i无法引用到设个方法?i=new CollegeStudent();
CollegeStudent name = new CollegeStudent();
name.study();
}
}
----------------解决方案--------------------------------------------------------
ISport接口中只有run这个方法,你用它来引用对象的时候,它也就只知道run,调用其它方法都是不可能的。子类是对父类的扩展,新的东西只有子类才知道。虽然实际的对象是子类,但是引用却是父类的。这就是多态了。
为什么LZ要在接口的名字前加一个I呢?不会是受到C#的影响吧?Java里面不流行这个。
----------------解决方案--------------------------------------------------------
回复 2楼 lz1091914999
ISport随手写的,上转型已经了解了,谢谢,这里好少?半天也木人回差点跑到休闲区发了!!! ----------------解决方案--------------------------------------------------------