Building Java Programs.ppt
《Building Java Programs.ppt》由会员分享,可在线阅读,更多相关《Building Java Programs.ppt(16页珍藏版)》请在麦多课文档分享上搜索。
1、Building Java Programs,Chapter 8 Lecture 8-2: Constructors and Encapsulationreading: 8.4 - 8.5 self-checks: #10-17 exercises: #9, 11, 14, 16,2,Object initialization: constructors,reading: 8.4self-check: #10-12 exercises: #9, 11, 14, 16,Initializing objects,Currently it takes 3 lines to create a Poin
2、t and initialize it:Point p = new Point(); p.x = 3; p.y = 8; / tediousWed rather pass the fields initial values as parameters:Point p = new Point(3, 8); / better!We are able to this with most types of objects in Java.,Constructors,constructor: Initializes the state of new objects.public type(paramet
3、ers) statements;runs when the client uses the new keyword does not specify a return type; it implicitly returns the new object being createdIf a class has no constructor, Java gives it a default constructor with no parameters that sets all fields to 0.,Constructor example,public class Point int x;in
4、t y;/ Constructs a Point at the given x/y location.public Point(int initialX, int initialY) x = initialX;y = initialY;public void translate(int dx, int dy) x += dx;y += dy; ,Tracing a constructor call,What happens when the following call is made?Point p1 = new Point(7, 2);,public Point(int initialX,
5、 int initialY) x = initialX;y = initialY; public void translate(int dx, int dy) x += dx;y += dy; ,Client code, version 3,public class PointMain3 public static void main(String args) / create two Point objectsPoint p1 = new Point(5, 2);Point p2 = new Point(4, 3);/ print each pointSystem.out.println(“
6、p1: (“ + p1.x + “, “ + p1.y + “)“);System.out.println(“p2: (“ + p2.x + “, “ + p2.y + “)“); / move p2 and then print it againp2.translate(2, 4);System.out.println(“p2: (“ + p2.x + “, “ + p2.y + “)“); OUTPUT: p1: (5, 2) p2: (4, 3) p2: (6, 7),Common constructor bugs,Accidentally writing a return type s
7、uch as void:public void Point(int initialX, int initialY) x = initialX;y = initialY;This is not a constructor at all, but a method!Storing into local variables instead of fields (“shadowing“):public Point(int initialX, int initialY) int x = initialX;int y = initialY;This declares local variables wit
8、h the same name as the fields, rather than storing values into the fields. The fields remain 0.,Multiple constructors,A class can have multiple constructors. Each one must accept a unique set of parameters.Write a constructor for Point objects that accepts no parameters and initializes the point to
- 1.请仔细阅读文档,确保文档完整性,对于不预览、不比对内容而直接下载带来的问题本站不予受理。
- 2.下载的文档,不会出现我们的网址水印。
- 3、该文档所得收入(下载+内容+预览)归上传者、原创作者;如果您是本文档原作者,请点此认领!既往收益都归您。
下载文档到电脑,查找使用更方便
2000 积分 0人已下载
下载 | 加入VIP,交流精品资源 |
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- BUILDINGJAVAPROGRAMSPPT
