Basics of OOP
Object-Oriented Programming (usually abbreviated as OOP) is a coding strategy that sets Java apart from many of its predecessors and compatriot languages.
Object-Oriented Programming is dividing up your code into Classes, whose data can be accessed by their Objects. It'll make more sense later.
Why use Object-Oriented Programming?
— OOP is very modular- you can easily change a single segment of your code without having to update dozens of lines of code across different files.
— OOP also lets you control the flow of your code. You can only let specific files access specific fields, keeping your data safe and secure. We won't be going over this much as we will not use it, but make sure to do some research on it.
OOP Example
Let's say you wanted to make a dungeon crawler with a ton of different characters and enemies in Java. You can make a new class- "Player" or whatever.
Constructors
In Java, we create objects by using the class's constructor. Like a method, the constructor can have parameters. You can think of the parameters as like- custom fields you can set for the player, like health, damage, etc. Here is an example of a constructor.
new Object(parameters) {
// do something with your variables
}
// constructor of player
new Player(String name, double damage, double health) {
}
// how you'd access the Player object
Player hero = new Player("Himmel the Hero", 10, 10);Fields
You know the variables you've been creating in Java? We'll call them fields from now on. By definition, a field is a variable created in a class. Each object can have its own fields, setting them apart from one another. But- how would you access these fields so you can modify them? Here are some strategies.
If you wanted to- let's say, get the health of the hero. You can do this:
Classes
Your class is a blueprint where sets of code that execute a certain task (the objects) are built off of. On their own, many classes do not run code, however when an object is needed they can send them, using their commands as needed.
Objects
woojin— what you're manipulating
what is this?
Instance Methods
woojin— how you manipulate them
Last updated