Java Encapsulation

Learn private variables, getters, and setters in Java.

TutorialsJava Tutorial › Java Encapsulation

Java Encapsulation

Learn private variables, getters, and setters in Java.

This lesson is part of the Softlookup Java tutorial for beginners. It includes a simple explanation, Java code example, common mistakes, and links to related Java lessons.

Java Example

class User {
  private String name;
  public void setName(String n) { name = n; }
  public String getName() { return name; }
}

How It Works

The example above shows the basic idea behind this Java topic. Java programs usually use classes, methods, and strongly typed variables to organize code.

Try It Yourself

  1. Install the Java JDK.
  2. Create a file named Main.java.
  3. Paste the Java example into the file.
  4. Compile it using javac Main.java.
  5. Run it using java Main.

Common Mistakes

  • Forgetting semicolons at the end of statements.
  • Using the wrong capitalization for class names or methods.
  • Saving the file with a name that does not match the public class.
  • Forgetting that Java is case-sensitive.

Related Java Lessons

Java Tutorial Home | Variables | Data Types | Methods | Classes | Objects