Object-Oriented PL/SQL: Bringing Java Paradigms to the Database
PL/SQL is inherently a procedural language, but it fully supports Object-Oriented Programming (OOP). Learn how to encapsulate logic using Object Types, Constructors, Member Methods, and Inheritance.
Why OOP in the Database?
Standard PL/SQL is procedural. You write standalone procedures and packages. But what if you are modeling complex business entities, like a Shape that calculates its own area, or a Customer that validates its own email format?
Oracle's Object Types allow you to bind data (attributes) and behavior (methods) together into a single, cohesive unit. You can pass these objects around as parameters, store them in variables, or even store them directly in relational columns!
Creating an Object Type (The Class)
Creating an Object in Oracle requires two steps, much like creating a Package: the Specification (the structure) and the Body (the implementation).
Let's create a blueprint for an EMPLOYEE_OBJ.
The Type Body (Methods & Constructors)
Now we implement the behavior in the Type Body.
Notice the SELF keyword. This is the exact equivalent of this in Java or C++. It refers to the specific instance of the object currently executing the method.
Instantiating Objects
To use the object, you must instantiate it using its implicit Constructor. Oracle automatically creates a constructor that takes all attributes as arguments.
Inheritance and Subtyping
Because we declared employee_obj as NOT FINAL, we can create Subtypes that inherit its attributes and methods. Let's create a MANAGER_OBJ.
Now we provide the body for the Manager, overriding the get_full_name method to include a "Manager" prefix.
Common Gotchas
Important Gotchas
- !
Oracle allows you to create tables out of Object Types (
CREATE TABLE emps OF employee_obj). Avoid this! It creates tight coupling between your database schema and your PL/SQL code. Changing an object type that is used in a table requires massive, painful data migrations. Stick to using Objects strictly as transient PL/SQL variables. - !
While you can overload methods in standard Packages, doing it in Object Types requires careful management of Custom Constructors to avoid ambiguous signature matches.
Key Takeaways
Key Takeaways
- Object Types allow you to encapsulate related attributes and behaviors.
- Use the
SELFkeyword inside Type Bodies to reference the current instance variables. - Use
NOT FINALto allow inheritance, andUNDERto create Subtypes. - Use Object Types for PL/SQL modeling, but avoid storing them directly in relational tables.


