Skip to Content
bytegarden

Object Oriented Programming

Core Principles

  1. Classes: Blueprint for creating objects that defines attributes and behaviors
  2. Objects: Instances of a class that represent real-world entities
  3. Abstraction: Hiding internal details and showing only required features
  4. Encapsulation: Bundling all related components into a single unit
  5. Inheritance (Specialization): Building upon existing features to create something new
  6. Polymorphism (Generalization): Ability to treat different specific types as one general type
AspectGeneralizationSpecialization
ApproachBottom-UpTop-Down
PurposeCreate a shared SuperclassCreate a more specific Subclass
FocusCombining common featuresAdding new features
Achieved byAbstract Classes, InterfacesInheritance
ResultGeneral SuperclassSpecialized Subclass
ExampleAll vehicles stopping at a red lightBasic car → Luxury car with extra features

Message Passing

  • Communication mechanism between objects in OOP
  • We mostly use Queue to implement communication between threads
  • Objects communicate by sending messages (method calls)
  • Fundamental to object collaboration
  • Types of Message Passing
    1. Synchronous (Blocking)
      • Sender waits for response
      • Like method calls that return values
    2. Asynchronous (Nono-blocking)
      • Sender waits for response
      • Like method calls that return values

Example of message passing

Object Identity

Object identity in Java refers to the unique identification of an object during its lifetime. Each object in Java has a unique identity that distinguishes it from all other objects

Identity vs Equality

  • Identity (==): Tests if two references point to the exact same object in memory

  • Equality (.equals()): Tests if two objects have the same content/state

  • Example:

    String s1 = new String("hello");
    String s2 = new String("hello");
    System.out.println(s1 == s2);        // false (different objects)
    System.out.println(s1.equals(s2));   // true (same content)

Object References

  • References are variables that point to objects in memory

  • Multiple references can point to the same object

  • When no references point to an object, it becomes eligible for garbage collection

  • Example:

    Person p1 = new Person("John");
    Person p2 = p1;                // Both p1 and p2 point to same object
    p1 = null;                     // Object still accessible through p2
    p2 = null;                     // Object now eligible for garbage collection

HashCode

  • Every object has a hashCode() method inherited from Object class
  • Returns an integer value that represents the object’s memory address
  • Contract between equals() and hashCode():
    • If two objects are equal, they MUST have the same hashCode
    • If two objects have same hashCode, they MAY or MAY NOT be equal

this vs super

  • super is used to call the parent class with its properties