Back to Using Objects

Lesson PreviewLesson 3 of 10 in this unit

2.2.2 Constructors, parameters, and methods

Part of Using Objects in AP® Computer Science A. Read the opening section, then create a free account for the full interactive lesson, practice, and progress tracking.

Constructors, parameters, and methods

Let’s say we want to make a program that can keep track of a point’s position with its public fields x, y, and z. Below is an example of how to track the point with directly accessing public fields:

java
public class Main {
    public static void main(String[] args) {
        Point point1 = new Point();
        point1.x = -4.6;
        point1.y = 7.8;
        point1.z = -1.5;
        //setting all of the coordinates on separate lines is verbose! If only there was a better way…
        System.out.println("The point is at ("+point1.x+", "+point1.y+", "+point1.z+")");
    }
}

Output

The point is at (-4.6, 7.8, 1.5)
java
public class Point {
    public double x, y, z;
}

Continue the full lesson in Stellar

Create a free account to unlock the remaining sections, checkpoints, course practice, and progress tracking for AP® Computer Science A.