3.3 - Anatomy of a Class
Data encapsulation means hiding a class’s implementation details from other classes. You control this with two keywords:
private: only accessible from within the declaring class
public: accessible from outside the class too
In this course, classes are always
public and declared with the class keyword. Constructors are always public too.public class Dog { private String name; // private, hidden from outside classes private int age; public Dog(String name, int age) { // public constructor this.name = name; this.age = age; } }
Each instance variable belongs to the object itself, meaning every object gets its own separate copy.
Dog a = new Dog("Rex", 3); Dog b = new Dog("Bella", 5); // a and b each have their own name and age. // Changing a's name later would not change b's name.
Good practice: keep your instance variables
private unless the class specification tells you otherwise. That’s what actually achieves encapsulation.Methods can be
public (accessible from inside or outside the class) or private (only accessible from inside the class).public class Dog { private String name; public String getName() { // public, accessible from anywhere return name; } private void logChange() { // private, only usable inside this class System.out.println("Name changed."); } }
Here’s what that looks like from a different class. Outside code can’t touch
private instance variables or call private methods, so it has to go through the public ones:public class Dog { private String name; public Dog(String n) { name = n; } public String getName() { return name; } public void setName(String newName) { name = newName; logChange(); // allowed: a private method can be called inside its own class } private void logChange() { System.out.println("Name changed."); } }
// Code in a different class, like a DogPark class Dog d = new Dog("Rex"); System.out.println(d.getName()); // Rex d.setName("Max"); // prints Name changed. System.out.println(d.name); // compile error: name has private access in Dog d.logChange(); // compile error: logChange() has private access in Dog
That’s the whole point of encapsulation: other classes only use the
public methods, so the Dog class stays in control of how its data is read and changed.