Object-Oriented Programming in Java: Classes and Objects

Object-Oriented Programming (OOP)

  • OOP revolves around the concept of objects as fundamental program elements.
  • Objects are characterized by properties (data) and behaviors (methods).
  • Physical objects can be modeled as software objects using properties as data and behaviors as methods.

Encapsulation

  • Encapsulation hides certain implementation details of a class.
  • It places a boundary around properties and methods to prevent unintended side effects.
  • This prevents programs from unexpectedly changing variables.

Classes and Objects

  • Class: A template, prototype, or blueprint for creating objects.
  • It's the fundamental structure in OOP.
  • Class members:
    • Fields (properties or attributes): specify data types defined by the class.
    • Methods: specify operations.
  • Object: An instance of a class.
    • Composed of data (properties/variables) describing characteristics.
    • Consists of methods (behavior) describing how it behaves.
  • Classes provide reusability, allowing programmers to create many objects from a single class.

Class vs. Object Example (Car)

  • Car Class:
    • Instance Variables: Plate Number, Color, Manufacturer, Current Speed
    • Instance Methods: Accelerate, Turn, Brake
  • Object Car A:
    • Plate Number: ABC 111, Color: Blue, Manufacturer: Mitsubishi, Current Speed: 50 km/h
  • Object Car B:
    • Plate Number: XYZ 123, Color: Red, Manufacturer: Toyota, Current Speed: 100 km/h

Class Variables (Static Member Variables)

  • Belong to the entire class, not specific objects.
  • Have the same value for all objects of the class.

Class Variable Example

  • Using the