Java Classes and Objects


What is a Class in Java?
  • A class is a blueprint or template for creating objects.
  • It defines properties (variables) and behaviors (methods) that the objects created from it will have.
  • Objects are the real-world entities created based on a class.

Example

    
    class Car {
        // Properties (Fields)
        String brand;
        int year;

        // Behavior (Method)
        void displayInfo() {
            System.out.println(brand + " - " + year);
        }
    }
    
    
  • Car is a class.
  • brand and year are fields (variables).
  • displayInfo() is a method (behavior).
Real Life Example
Real World In Java
"Car" is a category class Car {}
"BMW", "Tesla" are individual cars Car bmw = new Car(); Car tesla = new Car();
Why do we need Classes?
  • To organize code neatly.
  • To model real-world things in programming.
  • To allow Object-Oriented Programming (OOP) features like:
    1. Inheritance
    2. Polymorphism
    3. Encapsulation
    4. Abstraction