← Back to Core Java Course | Chapter 7: OOP Core | Lesson 2 of 11

Java Classes & Objects

Defining a Class

A class is a blueprint describing what data (fields) and behavior (methods) its objects will have, but no memory is actually allocated until you create an object from it — the class itself is just a template living in the JVM's metadata.

Example: Defining a Class

java
class Dog {
	String name;
	int age;
}
public class Main {
	public static void main(String[] args) {
		System.out.println("Class defined, no object yet");
	}
}

Instantiating Objects

The new keyword instantiates an object, running the constructor and allocating memory for that specific instance on the heap. Every call to new produces a distinct object, even if you pass identical constructor arguments each time.

Example: Instantiating Objects

java
class Dog {
	String name;
}
public class Main {
	public static void main(String[] args) {
		Dog dog1 = new Dog();
		Dog dog2 = new Dog();
		System.out.println(dog1 == dog2); // false: distinct objects
	}
}

Working with Instance Methods

Instance methods operate on a specific object's data and require an object reference to be called (obj.method()), which is what lets them directly read and modify that particular object's fields without you passing the object explicitly as a parameter.

Example: Working with Instance Methods

java
class Dog {
	String name = "Rex";
	void bark() {
		System.out.println(name + " says Woof!");
	}
}
public class Main {
	public static void main(String[] args) {
		Dog dog = new Dog();
		dog.bark();
	}
}

Object State Independence

Every object created from a class gets its own independent copy of the class's instance fields, so changing one object's state has zero effect on any other object of the same class — this is the core reason objects are useful for modeling separate, independent entities.

Example: Object State Independence

java
class Dog {
	String name;
}
public class Main {
	public static void main(String[] args) {
		Dog dog1 = new Dog();
		Dog dog2 = new Dog();
		dog1.name = "Rex";
		dog2.name = "Fido";
		System.out.println(dog1.name);
		System.out.println(dog2.name);
	}
}

Handling Null References

An object variable that hasn't been assigned (or has been explicitly set to null) doesn't point to any object at all; calling a method on it throws a NullPointerException at runtime. Checking for null before dereferencing is one of the most common defensive patterns in Java code.

Example: Handling Null References

java
class Dog {
	void bark() {
		System.out.println("Woof");
	}
}
public class Main {
	public static void main(String[] args) {
		Dog dog = null;
		if (dog != null) {
			dog.bark();
		} else {
			System.out.println("dog is null");
		}
	}
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.