Java is an object-oriented programming language. Objects are a fundamental concept in Java. In Java programs, programmers break down complex problems into smaller pieces using objects.
Think about everyday objects around you - a car, a phone, or a bank account. Each has properties (like color, brand, balance) and actions they can perform (like start, call, withdraw). Java objects work the same way.
Java programmers write code in classes, and when the program runs, objects are created from those classes.
Objects are instances of classes that encapsulate data (instance variables) and behavior (methods) together. Objects add tremendous power to Java and are fundamental to the language’s object-oriented design. In Java, everything except primitive types (int, double, boolean, etc.) are objects, including:
-
String objects
-
Collection objects (ArrayList, HashMap, etc.)
-
Custom class objects you create
Objects are used to model real-world entities and organize related data and methods together. Objects can contain other objects as instance variables, creating complex data structures and relationships. This composition allows for building sophisticated applications using well-organized, reusable components.
// Creating a Person object using a class
class Person {
String firstname;
String lastname;
int homedistrict;
String[] skills;
public Person(String firstname, String lastname, int homedistrict, String[] skills) {
this.firstname = firstname;
this.lastname = lastname;
this.homedistrict = homedistrict;
this.skills = skills;
}
// Getter methods
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
public int getHomedistrict() {
return homedistrict;
}
public String[] getSkills() {
return skills;
}
}
Person katniss = new Person("Katniss", "Everdene", 12,
new String[]{"foraging", "wildlife", "hunting", "survival"});We can imagine an object as a container which has copies of instance variables (or field) that can be different for each different object of the same class. Fields can be any Java data type at all. Let’s create a sample player object for a game:
// Creating a Player class with nested Weapons class
class Weapon {
String sword;
String bow;
int arrows;
public Weapon(String sword, String bow, int arrows) {
this.sword = sword;
this.bow = bow;
this.arrows = arrows;
}
}
class Player {
String name;
String species;
String superPower;
int lives;
Weapon weapon;
public Player(String name, String species, String superPower, int lives, Weapon weapons) {
this.name = name;
this.species = species;
this.superPower = superPower;
this.lives = lives;
this.weapon = weapons;
}
}
Player player1 = new Player("Rocco", "warrior", "flight", 4,
new Weapon("Excalibur", "Yew", 12));This 'player1' object has 5 instance variables. One of those instance variables is itself an object - the 'weapon' field contains a Weapon object with its own 3 instance variables.
In Java, you typically use getter and setter methods to access and modify instance variables (fields) of a class. This approach follows the principle of encapsulation, which helps protect the internal state of an object.
Suppose you have a Player class with a name field:
public class Player {
private String name; // instance variable
// Getter method
public String getName() {
return name;
}
// Setter method
public void setName(String newName) {
name = newName;
}
}-
Getter (
getName()): Returns the value ofname. -
Setter (
setName(String newName)): Updates the value ofname.
Player player1 = new Player();
player1.setName("Rocco"); // Set the name using the setter
System.out.println(player1.getName()); // Get the name using the getterGotcha:
Directly accessing fields (e.g., player1.name = "Rocco";) is only possible if the field is public.
Using getters and setters is safer and more flexible, especially if you want to add validation or logic later.
A Java object reference is like a label or pointer that tracks for your program
where to find an object in memory. (So you don’t have to)
When you create an object using new, Java stores it somewhere in memory,
and the variable you assign it to holds a reference
(not the actual object itself).
Example:
Airplane plane1 = new Airplane("Boeing", 900, 200, 0);Here, plane1 is an object reference.
It doesn’t contain the Airplane object itself, but it knows where to find it in memory.
Airplane plane2 = plane1;Now both references point to the same object. Changing the object through one reference affects the other.
Key points:
-
Object references store the location of objects, not the objects themselves
-
Multiple references can point to the same object
-
Changing the object through one reference is visible through all references to that object
-
This is different from primitive types (like int or double), which store actual values, not references
If we have an object:
class Airplane {
String type;
double topSpeed;
int passengerLimit;
int passengersOnboard;
String destination;
String origin;
public Airplane(String type, double topSpeed, int passengerLimit, int passengersOnboard) {
this.type = type;
this.topSpeed = topSpeed;
this.passengerLimit = passengerLimit;
this.passengersOnboard = passengersOnboard;
}
// Getter methods
public String getDestination() {
return destination;
}
public String getOrigin() {
return origin;
}
public int getPassengersOnboard() {
return passengersOnboard;
}
// Setter methods
public void setDestination(String destination) {
this.destination = destination;
}
public void setOrigin(String origin) {
this.origin = origin;
}
public void setPassengersOnboard(int passengersOnboard) {
this.passengersOnboard = passengersOnboard;
}
}
Airplane airplane512 = new Airplane("airbusA330", 0.86, 253, 0);We have built a plane object.
Airplane flight77 = airplane512; // I'm assigning a plane to a flight
flight77.setDestination("Tokyo");
flight77.setOrigin("Seattle");
// now watch carefully...
flight77.setPassengersOnboard(120);
// and if I print out some of the instance variables...
System.out.println(airplane512.getPassengersOnboard()); // 120
System.out.println(flight77.type); // airbusA330
System.out.println(airplane512.type); // airbusA330This is because both flight77 and airplane512 _refer to the same object. so when you make changes through the flight77 name, the properties in the object change, and you can get and/or set properties through the airplane512 name as well. This proves very powerful in many cases.
This can also be confusing if you accidentally create multiple references when you meant to create separate objects.
As we have said, to make things even more powerful, Java objects can have methods attached to them. Let’s build a special counter object, something we might use in a program or app somewhere.
As you may be aware, in American football there are four common changes to a team’s score during a game:
import java.util.HashMap;
import java.util.Map;
class ScoreCounter {
private Map<String, Integer> options;
private int score;
public ScoreCounter() {
options = new HashMap<>();
options.put("fieldgoal", 3);
options.put("touchdown", 6);
options.put("point_after_touchdown", 1);
options.put("safety", 2);
score = 0;
}
public void touchdown() {
this.score += this.options.get("touchdown");
}
public void fieldgoal() {
this.score += this.options.get("fieldgoal");
}
public void pat() {
this.score += this.options.get("point_after_touchdown");
}
public void safety() {
this.score += this.options.get("safety");
}
public int getScore() {
return this.score;
}
}
// Example usage:
public class Main {
public static void main(String[] args) {
ScoreCounter scoreCounter = new ScoreCounter();
// You can now use scoreCounter here
}
}We can use that object, with its methods like this:
scoreCounter.touchdown(); // add 6
scoreCounter.pat(); // add 1
scoreCounter.fieldgoal(); // add 3
System.out.println(scoreCounter.getScore()); // ??This class has two data properties (options and score) and five action methods. These functions are called methods - they are functions that belong to an object. You call (or invoke) methods on objects to make them perform actions.
Notice the this keyword. It refers to the current object - the specific object whose method is being called.
For example, when you call scoreCounter.touchdown(), inside that method this refers to the scoreCounter object.
We have tried to give you some of the very basic parts of OOP in Java, for you to get a very basic understanding of coding in Java.
There are a number of very powerful things we have left out of this discussion about Java objects.
We also have not discussed extremely powerful concepts like lambdas and streams. But rest assured, there is much much more for you to learn about Objects in Java.
Master what we’ve written about here and then forge ahead into more complicated and powerful capabilities.
There is much more to learn about Java objects, but you now have the foundation to build upon. Keep practicing with objects and methods - they’re the building blocks of Java programming.