Welcome 微信登录

首页 / 软件开发 / JAVA / Java的接口和继承

Java的接口和继承2013-12-05 csdn BruceZhang1.JAVA里没有多继承,一个类只能有一个父类。而继承的表现就是多态。一个父类可以有多个子类,而在 子类里可以重写父类的方法(例如方法print()),这样每个子类里重写的代码不一样,自然表现形式就不一 样。这样用父类的变量去引用不同的子类,在调用这个相同的方法print()的时候得到的结果和表现形式就不 一样了,这就是多态,相同的消息(也就是调用相同的方法)会有不同的结果。举例说明:

//父类public class Father{//父类有一个打孩子方法public void hitChild(){ System.out.println("臭崽子,你站着,不打你我不是你爹!");}}}//子类1public class Son1 extends Father{//重写父类打孩子方法public void hitChild(){System.out.println("为什么打我?我做错什么了!");}}//子类2public class Son2 extends Father{//重写父类打孩子方法public void hitChild(){System.out.println("我知道错了,别打了!");}}//子类3public class Son3 extends Father{//重写父类打孩子方法public void hitChild(){System.out.println("我跑,你打不着!");}}//测试类public class Test{public static void main(String args[]){Father father;father=new Father();father.hitChild();father = new Son1();father.hitChild();father = new Son2();father.hitChild();father = new Son3();father.hitChild();}}
运行结果

C:java>java Test

臭崽子,你站着,不打你我不是你爹!为什么打我?我做错什么了!我知道错了,别打了!我跑,你打不着!
都调用了相同的方法,出现了不同的结果!这就是多态的表现!

2.JAVA 中没有多继承,而用接口实现了多继承!一个类或是可以同时实现多个接口!(就相当于C++里一个类同时继 承了多个类!)例如:

public class Son implements Father1,Father2,Father3

{

}