Recap

CSCI 1913 – Introduction to Algorithms, Data Structures, and Program Development
Adriana Picoral

Encapsulation

  • Core principle of Object-Oriented Programming (OOP)
  • Objects are instances of a class, and an object is a unit with its data (variables) and the methods that operate on that data
  • Encapsulation restricts direct access to an object’s internal state and provides controlled access through well-defined methods

Encapsulation

  • private instance variables (data hiding)
  • Getters and Setters (controlled access)

Benefits: modularity, easier to test and maintain, data integrity and validation, flexibility in refactoring

Inheritance

Use keyword extends to extend a parent class and create a subclass

  • subclass inherits instances and methods from super (parent) class
  • subclass has a constructor obligation with parent class (parent constructor always runs)
  • use super(params) in subclass constructor (needs to be first line) to satisfy parent class constructor requirements
  • use super.method() or super.variableName to access public or protected members of parent class

A good parent class

careful use of privacy:

  • public “how outsiders use my family”
  • protected “provided to my children”
  • private “I’ll handle this myself”

Gives structure and design to children

Designed with polymorphism in-mind

Polymorphism

  • Method overloading – methods with same name but different signatures in the same class
  • Method overriding – methods with the same name and signature in parent-child classes (we often override toString() and equals(Object obj))

Important syntax

instanceof – evaluates to true if and only if reference is a member of Type

variableName instanceOf Type

We use instanceof together with type casting

(SubClass) parClassVariableName

Converts a parent-class-reference (storing a child class) to a child-class reference (no actual conversion) – purpose is to call methods in subclass