Java Classes & Objects
In this page:
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
class Dog {
String name;
int age;
}
public class Main {
public static void main(String[] args) {
System.out.println("Class defined, no object yet");
}
}
Login to try C/C++/Java/PHP code in the editor
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
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
}
}
Login to try C/C++/Java/PHP code in the editor
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
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();
}
}
Login to try C/C++/Java/PHP code in the editor
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: