07 - Introduction to Object-Oriented Programming
Learn the fundamentals of classes and objects in Java.
Object-Oriented Programming (OOP) is the foundation of Java and Hytale modding. Instead of just having variables and methods floating around, we organize them into classes and objects.
What is a Class?
A class is a blueprint for creating objects. Think of it like a recipe or a template.
What is an Object?
An object is an instance created from a class. If a class is a blueprint, an object is the actual thing built from that blueprint.
Class = Blueprint (the idea of a player) Object = Actual thing (Alice, Bob, specific players)
One class can create many objects, just like one recipe can make many cakes!
Creating a Simple Class
Let's create a Sword class for Hytale:
Using the class:
Constructors
Instead of setting properties one by one, use a constructor to initialize objects:
Now creating swords is easier:
- Same name as the class
- No return type (not even
void) - Called automatically when you use
new - Can have multiple constructors (overloading)
The this Keyword
this refers to the current object. Use it to clarify when parameter names match property names:
Without this, Java gets confused:
Practical Examples
Item Class
public class Main {
public static void main(String[] args) {
Item potion = new Item("Health Potion", "Consumable", 5, 0.5);
potion.use(); // Used Health Potion. Remaining: 4
System.out.println("Total weight: " + potion.getTotalWeight()); // 2.0
}
}Monster Class
Block Class
Access Modifiers (Preview)
You've seen public - it means "anyone can access this". We'll learn more about access control later, but here's a preview:
For now, use public for everything. We'll learn when to use private in the next article.
Classes help you:
- Organize related data and methods together
- Reuse code easily (create many objects from one class)
- Model real-world things (players, items, monsters)
- Maintain code (changes in one place affect all objects)
Without classes, managing 100 players would require 100 separate variables for each property. With classes, it's just 100 Player objects!
Practice Exercises
-
Create a
PotionClass:- Properties: name, healAmount, uses
- Constructor to set all properties
- Method
drink()that heals and decreases uses - Method
isEmpty()that returns true if uses less than or equal to 0
-
Create a
ChestClass:- Properties: isLocked, itemCount, capacity
- Constructor
- Method
addItem()that checks capacity - Method
unlock()that sets isLocked to false - Method
isFull()that checks if itemCount >= capacity
-
Create a
VillagerClass:- Properties: name, profession, tradeCount
- Constructor
- Method
greet()that prints a greeting - Method
trade()that increases tradeCount - Method
getInfo()that displays all properties
-
Create Multiple Objects: Using any class you made, create 3 different objects and test all their methods.