Concept Explanation
Object-Oriented Programming (OOP) is a way to organize code so it mirrors the real world.
- Class: A Blueprint or template. (e.g., The architectural drawing for a house).
- Object: A Physical House built from that blueprint.
You can build 1,000 houses from one blueprint, but each house might have different furniture (data).
Syntax or Core Structure
// The Blueprint
public class Robot {
String name;
int batteryLevel;
public void sayHi() {
System.out.println("Beep Boop, I am " + name);
}
}
// The physical building (Usage)
public class Main {
public static void main(String[] args) {
Robot r1 = new Robot(); // Using the 'new' keyword to build
r1.name = "Sparky";
r1.sayHi();
}
}
Best Practices
- One Class per File: Usually, each
publicclass gets its own.javafile. - Noun Naming: Classes should be nouns (
User,Order), and methods should be verbs (save,delete). - Keep it Focused: A class should represent one concept. Don't put "User" and "Payment" logic in the same class.
Practice Exercises
- The Dog Designer: Create a
Dogclass with attributes (Breed, Age, Color) and a methodbark(). - Multiple instances: Create two different
Robotobjects with different names and print their stats. - The Remote: Create a
RemoteControlclass that has a booleanisOnand a methodtoggle()to flip it.