第7章 Ja的va 对象 - 副本.ppt

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

* 【示例】将this作为当前对象用于方法的实际参数 class A { int x, y; A(int ax, int y) { x=ax; y=ay; } void showA( ) { B b=new B( ); b.showB( this ); //需要将当前对象作为实参 } } 因此,如果你需要将当前对象作为某个方法的实际参数时, 你便可以利用this来实现之。 class B { void showB(A a){System.out.println(“x=“+a.x+”;y=“ +a.y);} } class TestThis{ public static void main(String[] arg){ A aa = new A( 10, 20 ); aa.showA( ); } } 运行结果: x=10 y=20 该this将是调用 方法showA()的 当前对象的引用! * 2. 在构造方法中,this将表示调用本类中的另一个构造方法。 【示例】使用this调用另一个构造方法 class Employee{ private String name; private double salary; private int id; private static int nextId=1; Employee (String n, double s) { name=n; salary=s; id=nextId++; } Employee (double s), { this(“Employee #”+nextId, s) ; } void showEmployee() { System.out.println(name+“,”+id+”,”+salary); } } class TestConstructor{ public static void main(String[] arg){ Employee e1=new Employee (henly, 2000 ); e1.showEmployee(); Employee e2=new Employee (1000); e2.showEmployee(); } } 说明: 若要在构造方法中调用另一个构造方法,则必须出现在第一句! 运行结果: henly,1,2000 Employee #2,2,1000 * 注意: 若要在构造方法中调用另一个构造方法,则必须出现在第一句! class Employee{ private String name; private double salary; private int id; private static int nextId=1; Employee (String n, double s) { name=n; salary=s; id=nextId++; } Employee (double s), { this(“Employee #”+nextId, s); } void showEmployee() { System.out.println(name+“,”+id+”,”+salary); } } 2. 在构造方法中,this将表示调用本类中的另一个构造方法。 运行结果: henly,1,2000 Employee #2,2,1000 class TestConstructor{ public static void main(String[] arg){ Employee e1=new Employee (henly, 2000 ); e1.showEmployee(); Employee e2=new Employee (1000); e2.showEmployee(); } } * 在介绍包之前,先让我们再来回顾一下关于“源程序文件” 和“类文件”的概

文档评论(0)

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

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

1亿VIP精品文档

相关文档