JAVA - Zero to Hero / Object Oriented Programming (OOP)

Classes and Objects

πŸ§‘β€πŸ’» What is a Class?

  • A class is a blueprint or template for creating objects.

  • It defines properties (variables) and behaviors (methods).

class Car {
    String color;        // property
    void drive() {       // method
        System.out.println("The car is driving");
    }
}

πŸ—‚οΈ What is an Object?

  • An object is a real instance of a class.

  • You use the new keyword to create an object.

Car myCar = new Car();

Example: Class + Object

class Animal {
    String name;

    void sound() {
        System.out.println(name + " makes a sound.");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal a = new Animal();   // object created
        a.name = "Dog";            // setting property
        a.sound();                 // calling method
    }
}
Dog makes a sound.

πŸ” Why Use Classes and Objects?

  • Reuse code easily

  • Group related data and functions

  • Create multiple instances (objects) from one class

βœ… Recap

Term

Meaning

Class

Blueprint that defines variables & methods

Object

Instance created from a class

new

Keyword used to create an object