Building Java Programs .edu
Building Java Programs
Chapter 8 Lecture 8-2: Constructors and Encapsulation
reading: 8.3 - 8.4
Copyright 2008 by Pearson Education
Object initialization: constructors
reading: 8.4 self-check: #10-12 exercises: #9, 11, 14, 16
2
Copyright 2008 by Pearson Education
Initializing objects
Currently it takes 3 lines to create a Point and initialize it:
Point p = new Point(); p.x = 3; p.y = 8;
// tedious
We'd 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.
3
Copyright 2008 by Pearson Education
Constructors
constructor: Initializes the state of new objects.
public type(parameters) { statements;
}
runs when the client uses the new keyword does not specify a return type;
it implicitly returns the new object being created If a class has no constructor, Java gives it a default constructor
with no parameters that sets all fields to 0.
4
Copyright 2008 by Pearson Education
Constructor example
public class Point { int x; int 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;
} }
5
Copyright 2008 by Pearson Education
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related download
- chapter 11 section 8
- trigonometric substitutions math 121 calculus ii clark university
- cse 142 spring 2013 edu
- square roots via newton s method mit mathematics
- hw5 ap review due 4 24 name
- objectives loudoun county public schools
- 4 5 linear dependence and linear independence purdue university
- theorem the square root of a chi square n random mathematics
- 2004 ap calculus ab form b scoring guidelines college board
- ap calculus ab 1998 scoring guidelines college board
Related searches
- java programs examples with output
- java programs for practice
- free java programs examples
- java programs with output pdf
- java programs with source code
- basic java programs for beginners
- java programs on arrays
- java programs for beginners
- practice java programs for beginners
- java programs example
- java programs for beginners pdf
- practice java programs online