Skip to main content

1. OO and Java Programming Refresher (1)

07/10/22

Basic OO Concepts

  • Abstraction: Simple things like objects represent more complex underlying code and data
  • Encapsulation: The ability to protect some components of the object from external access
  • Inheritance: The ability for a class to extend or override functionality of another class
  • Polymorphism: The provision of a single interface to entities of different types
    • Compile time polymorphism: Method overloading
    • Run time polymorphism: Method overriding

Encapsulation

  • Hiding the implementation details of a class (all fields and helper methods private)
  • Helps with program maintenance: a change in one class does not affect other classes
  • A client of a class interacts with the class only through well-documented public constructors and methods; this facilitates team development

"this"

  • Refers to the implicit parameter inside the class

Constructors

  • Constructors of a class can call each other using the keyword "this" (this can avoid code duplicating)
  • Constructors are invoked using the operator new.
  • Parameters passed to "new" must match the number, types and order of parameters expected by one of the constructors

Passing Data

  • Passing by value: Copying of data, where changes to the copied value are not reflected in the original value
  • Passing by reference: aliasing of data, where changes to the aliased value are reflected in the original value
  • Value associated with an object is actually a pointer, called an object reference. These are passed by value

Overloaded Methods

  • Methods of the same class that have the same name but different numbers or types of parameters are called overloaded methods
  • Compiler treats these as completely different methods
  • The compiler knows which one to call based on the number and the types of the parameters passed to the method
  • The return type alone is not sufficient for making a distinction between overloaded methods

Static Fields

  • Static field (class field or variable): is shared by all objects of the class. Normally stored with class code, separately from instance variables
  • Non-static field (instance field or instance variable): belongs to an individual object.
  • Usually static fields are NOT initialised in constructors; either in declarations or in public static methods or just use their default value.
  • If a class has only static fields, there is no point in creating objects of that class, all of them would be identical.

Static Methods

  • Can access and manipulate class's statics fields. Belong to the class, not an instance of it.
  • Static methods cannot access instance fields or call methods of the class; instance methods can access all fields and call all methods of their class - both static and non static
  • Usually take input from the parameters, then return some value