四用java实现继承与派生.PPT

  1. 1、本文档共24页,可阅读全部内容。
  2. 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
四用java实现继承与派生

实验二 继承与派生 一、继承的概念 父类或超类:实际上是所有子类的公共域和公共方法的集合。 子类:父类的特殊化,是对公共域和方法在功能、内涵方面的扩展和延伸 ,祖先类的所有成员均将成为子类拥有的“财富” 。 Object类是所有类的祖先 。 Java实现继承与派生 【例1】类的继承中构造方法的调用测试 import java.awt.Color; public class Point { private int x, y; public Point(int x, int y) { //有参构造方法 this.x = x; this.y = y; } public Point() { // 无参构造方法 this(0,0); // 用this调用本类的另一构造方法 } public String toString() { String s = 点: + x + ,+ y; return s; } public static void main(String[ ] args) { Point p1=new Point(); System.out.println(p1.toString()); } } this代表当前对象 【例1】续 public class Pixel extends Point { Color c; public Pixel(int x,int y,Color c) { super(x,y); //用super调用父类的构造方法 this.c=c; } public String toString() { ?? return super.toString() +“颜色:”+c;   // 用super访问父类的方法 } public static void main(String a[ ]) { Pixel x=new Pixel (3,24,Color.blue); System.out.println(x); } } super代表父类对象 【注意】使用this查找匹配的方法时首先在本类查找,找不到时再到其父类和祖先类查找;使用?super?查找匹配方法时,首先到直接父类查找,如果不存在,则继续到其祖先类逐级往高层查找。 完整参考程序: import java.awt.Color; public class Point { private int x, y; public Point(int x, int y) { //有参构造方法 this.x = x; this.y = y; } public Point() { // 无参构造方法 this(0,0); // 用this调用本类的另一构造方法 } public String toString() { String s = 点: + x + ,+ y; return s; } public static void main(String[ ] args) { Point p1=new Point(); System.out.println(p1.toString()); Pixel p2=new Pixel(10,20,Color.red); System.out.println(p2.toString()); } } class Pixel extends Point { Color c; public Pixel(int x,int y,Color c) { super(x,y); //用super调用父类的构造方法 this.c=c; } public String toString() { return super.toString() +颜色:+c; // 用super访问父类的方法 } } } 参考程序 请分析下列程序 import java.awt.Color; public class JavaPoint { public static void main(String[] args) {   Point p1=new Point(); System.out.print

文档评论(0)

fengruiling + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档