网站大量收购独家精品文档,联系QQ:2885784924

Java1_2_3Java1_2_3.ppt

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

【例3.4】构造方法的使用。 class Rect { int height; //定义成员变量 int width; Rect(int a,int b) //构造方法 { height=a; width=b; } void showArea() //定义成员方法 { System.out.println(面积=+height*width); } } public class Ex { public static void main(String args[]) { Rect r=new Rect(2,3); //创建对象r时自动调用构造方法 r.showArea(); } } 本程序的运行结果是: 面积=6 ◆方法重载 方法重载是面向对象的程序设计中多态性的一种表现 形式,是在类定义中存在两个或以上的同名成员方法,为了 使编译器能区分出同名的成员方法,同名成员方法的参数个 数或参数的数据类型是不同的。 【例3.5】同一个类中的方法重载。 class Rect { int height; //定义成员变量 int width; Rect(int a,int b) { height=a; width=b; } void showArea() //定义成员方法showArea() { System.out.println(面积=+height*width); } void showArea(int a) //定义成员方法showArea(),方法重载 { System.out.println(面积=+(height*width-a)); } } public class Ex { public static void main(String args[]) { Rect r=new Rect(2,3); //创建对象r时自动调用构造方法 r.showArea(); r.showArea(4); } } 本程序的运行结果是: 面积=6 面积=2 思考: 能不能在【例3.5】中增加一个如下的成员方法重载? int showArea() { return height*width; } ◆构造方法重载 【例3.6】构造方法重载的使用。 class Rect { int height; //定义成员变量 int width; Rect() { height=5; width=5; } Rect(int a,int b) { height=a; width=b; } void showArea() //定义成员方法 { System.out.println(面积=+height*width); } } public class Ex { public static void main(String args[]) { Rect r1=new Rect(2,3); //自动调用有参构造方法r1.height=2,r1.width=3 r1.showArea(); Rect r2=new Rect(); //自动调用无参构造方法 r2.height=5,r2.width=5 r2.showArea(); } } 本程序的运行结果是: 面积=6 面积=25 【 3.3 对象 】 对象是类的实例,类是对象的模板。 ◆创建对象 通过点运算符(.)操作对象的成员变量,调用成员方法。 ◆使用对象 r.height=100; r.showArea(); ◆对象的引用 Rect r1=new Rect(2,3); Rect r2=r1; r1=null; ◆对象的引用 因为对象r1重新赋值,所以其值不再是new关键字所分配的地址,而是null,但对象r2依旧指向new关键字所分配的地址。 ◆对象作为参数 【例3.7】对象作为参数使用。 class Rect { int height; //定义成员变量 int width; Rect(int a,int b) { height=a; width=b; } int area() //定义成员方法 { return height*width; } bool

您可能关注的文档

文档评论(0)

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

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

1亿VIP精品文档

相关文档