Java Tutorial

Classes & Objects

Encapsulation, constructors, the 'this' keyword, and instance members

What are Java Classes?

In Java, a class is a blueprint (a template) for an object. It defines two things:
  1. Attributes (Data/Fields): What the object "knows."
  2. Methods (Behavior/Actions): What the object "can do."
java
public class User {
    // Attributes!
    String name;
    int age;

    // A simple method!
    public void greet() {
        System.out.println("Hi, I'm " + name + "!");
    }
}

Creating an Object (new)

An object is a "real-world" instance of a class that actually exists in your computer's memory. You create an object using the new keyword.
java
// Create an instance!
User u1 = new User();
u1.name = "Alpha"; // Set values!
u1.greet(); // Run methods!

Constructors

A constructor is a special "method" that is called automatically when an object is created. It has the SAME name as the class and NO return type!
java
public class User {
    String name;

    // Constructor!
    public User(String n) {
        // Set name during creation!
        name = n; 
    }
}

User u1 = new User("Alpha");

The "this" Keyword

Wait! What if your parameter has the same name as your attribute? Use this to tell the computer you mean the attribute on the CURRENT object.
java
public class User {
    String name;

    public void setName(String name) {
        // this.name = The class attribute!
        // name = The method parameter!
        this.name = name; 
    }
}

Summary

TermDescription
ClassThe blueprint for your data
ObjectThe actual instance you use
FieldVariable belonging to a class
MethodFunction belonging to a class
ConstructorUsed to initialize data members
newThe keyword used to create an object
thisRefers to the current object instance
nullRepresents an uninitialized object
Best ForModeling real-world entities, managing state
OOPEncapsulation, Abstraction, Inheritance, Polymorphism
MemberGeneral name for attributes and methods
StateThe current values of an object's fields
BehaviorThe logic inside an object's methods
IdentityEach object has a unique memory address
Accessu1.name (Accessing with the dot operator!)
EncapsulateKeeping your data private (See Encapsulation section!)
StaticShared across ALL instances of the class
InheritDeriving one class from another!
OverloadDefine multiple constructors with different inputs
MemoryObjects live on the "Heap" memory
Garbage CObjects are auto-deleted when no one refers to them!
ReferenceUser u1 is a reference; new User() is the object!
AnonymousCreating an object without saving it to a variable!
FactoryA method that creates and returns objects
SingletonLimit instance count to ONLY one per app