首页
论坛
图书
开发资料
在线文档
网址
下载
联系我们
 新闻│Java│JavaScript│Eclipse│Eclipse 英文│J2EE│J2ME│J2SE│JSP│Netbeans│Hibernate│JBuilder│Spring│Struts
站内搜索: 请输入搜索关键词

当前页面: 开发资料首页 → Java 专题 → Java继承与派生时的多态性与方法重写

Java继承与派生时的多态性与方法重写

摘要: Java继承与派生时的多态性与方法重写

</td> </tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="485" height="86" align="center" valign="top">

一、基本概念:
① 静态多态性(编译时的特性),Java中的静态多态性实现手段-----重载函数。其调用规则是依据对象在定义时的类型相应地调用对应类中的重载函数
② 动态多态性(运行时的特性),Java中的动态多态性实现手段---覆盖(替换)基类中的同名成员函数(函数原型一致)。 其调用规则是依据对象在实例化时而非定义时的类型相应地调用对应类中的同名成员函数。
③ 父类与子类对象编程规则(赋值兼容原则):子类的对象可当着父类的对象来使用。

二、应用实例:


class Base{

 public void fun(){

   System.out.println("Base Class fun()");

 }

 public void fun(int X){

    System.out.println("Base Class fun(int x)");

 }

}

public class Derived extends Base{

  public void fun(int x,int y){

    System.out.println("Derived Class fun(int x,int y)");

  }

  public void fun(){

    System.out.println("Derived Class fun()");

  }

  public static void main(String[] args){

   Base obj=new Base();

   obj.fun(); //调用基类中的fun()

   // obj.fun(1,2); 错误

   obj=new Derived();

   obj.fun(); //调用派生类中的fun()

   obj.fun(1); //调用基类中的fun(int x)

   // obj.fun(1,2); 错误

    Derived ObjD=new Derived();

    ObjD.fun(1,2); //调用派生类中的fun(int x,int y)

    ObjD.fun(); //调用派生类中的fun()

    ObjD.fun(1); //因派生类中未定义出,则调用从基类中继承类来的

 }

}

三、继承与派生时的方法重写权限要求:重写的方法的访问权限不能有比基类更严格
的访问权限和定义出更多的例外。
例如: class Base{
public void fun() throws IOException{
}
}

class Derived extends Base{
//错误! 重写的方法的访问权限不能有比基类更严格的访问权限和更多的例外定义
private void fun() throws IOException,InterruptedException{
}
}

考考你(10):

What is the output of the following program?
1. class Base {
2. int x=3;
3. public Base() {}
4. public void show() {
5. System.out.print(" The value is " +x);
6. }
7. }

8. class Derived extends Base {
9. int x=2;
10. public Derived() {}
11. public void show() {
12. System.out.print(" The value is " +x);
13. }
14. }

15. public class Test {
16. public static void main(String args[]) {
17. Base b = new Derived();
18. b.show();
19. System.out.println("The value is "+b.x);
20. }
21. } // end of class Test
a. The value is 3 The value is 2
b. The value is 2 The value is 3
c. The value is 3 The value is 3
d.The value is 2 The value is 2 点击观看答案

</td> <td width="199" valign="top"> </td> </tr> <tr> <td height="20" colspan="2">


</td> </tr> </table>

 


function TempSave(ElementID) { CommentsPersistDiv.setAttribute("CommentContent",document.getElementById(ElementID).value); CommentsPersistDiv.save("CommentXMLStore"); } function Restore(ElementID) { CommentsPersistDiv.load("CommentXMLStore"); document.getElementById(ElementID).value=CommentsPersistDiv.getAttribute("CommentContent"); } </td> </tr> <tr>


↑返回目录
前一篇: Java技巧:在屏幕上定位窗口
后一篇: 一个有趣的字符动画

首页 | 全站 Sitemap | 联系我们 | 设为首页 | 收藏本站
版权所有 Copyright © 2006-2007, Java 编程资料牛鼻站, All rights reserved