Step 1 of 7 · Reading · ~3 min
Learn
Methods and Classes
Classes
A class bundles data (fields) with the operations on that data (methods). An object is one concrete thing built from the class. By the end of this lesson you can define a class, create objects from it, protect its data with private, and explain what two variables pointing at the same object means.
A class and its objects
static class Rectangle {
private int width;
private int height;
Rectangle(int width, int height) { // constructor
this.width = width;
this.height = height;
}
int area() {
return width * height;
}
boolean isSquare() {
return width == height;
}
}
Rectangle r = new Rectangle(3, 4);
System.out.println(r.area()); // 12
System.out.println(r.isSquare()); // false
The parts:
- Fields
widthandheight: everyRectanglehas its own pair. - Constructor: same name as the class, no return type.
new Rectangle(3, 4)allocates the object, runs the constructor, and hands back a reference to it. - Methods
area()andisSquare(): they run on an object, so they can read its fields directly. Unlike thestatichelpers from the last lesson, you call them through an object:r.area().
In this course your classes are written inside Main as static class Name { ... }. A nested class without static belongs to an instance of Main, and static main has no such instance to build it from.
this
Inside an instance method, this is the object the method was called on. In the constructor above, parameters share the names of fields, and the parameter wins inside the method, so this.width = width; says "set the field from the parameter". Write width = width; and you assign the parameter to itself while the field keeps its default 0.
Encapsulation: private fields, public behavior
private means "visible only inside this class". Keep fields private and let code outside change them only through methods, so the class can refuse bad changes:
void grow(int by) {
if (by > 0) { // the class guards its own rules
width += by;
height += by;
}
}
If width were public, any code could set it to -5. With a private field, every change goes through a method that can check it. Reading a private field uses a getter: int getWidth() { return width; }.
Objects are references
A variable of class type holds a reference to an object, not the object:
Rectangle alias = r; // a second name for the SAME object
alias.grow(2);
System.out.println(r.area()); // 30: r changed too (5 x 6)
Contrast with int: copying an int copies the value. Copying an object variable copies the arrow. == on two object variables asks "same object?", so two rectangles with identical sizes are ==-different unless they are one object. A variable that points at nothing is null, and calling a method on it throws NullPointerException.
toString
Printing an object calls its toString(). The default prints something like Main$Rectangle@1b6d3586. Write your own toString() in the class for readable output (the inheritance lesson explains exactly how this replaces the default):
public String toString() {
return width + "x" + height;
}
Now System.out.println(r) prints 3x4. (Java has a record shortcut for such data classes, but it is newer than the compiler behind this grader, so write the full class here.)
Common mistakes
width = width;in a constructor instead ofthis.width = width;.- Public fields everywhere, so no class can protect its own rules.
- Forgetting
new:Rectangle r;is anullreference, not an object. - Nested class without
staticused frommain. - Comparing objects with
==when you mean equal contents.
Your exercise
Model a bank account as a class. The balance must be private, and the rules about what a deposit or withdrawal may do belong inside the class, not in the code that uses it. The provided main runs a list of commands against one account; you write the class it relies on.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…