Lecture 7/15: Object-Oriented Programming

July 15, 2020

📂Associated files

  • Lecture15.zip
  • Lecture15_Slides.pdf

Lecture 15: Object-Oriented Programming

Cs 106b: programming abstractions, summer 2020, stanford university computer science department, lecturers: nick bowman and kylie jue.

The Stanford Campus

For every lecture, we will post the lecture slides and any example code that will be used during lecture, usually in advance of the beginning of the lecture. For today's lecture, you can find the slides below:

  • Lecture Slides
  • Lecture Code

After the conclusion of each lecture, we will upload the lecture recording to the "Cloud Recordings" tab of the "Zoom" section of Canvas. The lecture recordings will also be linked here for your convenience.

  • Lecture Recording

© Stanford 2020 · Website by Julie Zelenski · Page updated 2020-Jul-15

Object-oriented programming (OOP) is a fundamental programming paradigm used by nearly every developer at some point in their career. OOP is the most popular programming paradigm used for software development and is taught as the standard way to code for most of a programmer’s educational career. Another popular programming paradigm is functional programming, but we won’t get into that right now.

Today we will break down the basics of what makes a program object-oriented so that you can start to utilize this paradigm in your algorithms, projects, and interviews.

Now, let’s dive into these OOP concepts and tutorials!

Here’s what will be covered:

What is Object-Oriented Programming?

Building blocks of oop.

  • Four principles of OOP
  • What to learn next

Object-Oriented Programming (OOP) is a programming paradigm in computer science that relies on the concept of classes and objects . It is used to structure a software program into simple, reusable pieces of code blueprints (usually called classes), which are used to create individual instances of objects. There are many object-oriented programming languages, including JavaScript, C++ , Java , and Python .

OOP languages are not necessarily restricted to the object-oriented programming paradigm. Some languages, such as JavaScript, Python, and PHP, all allow for both procedural and object-oriented programming styles.

A class is an abstract blueprint that creates more specific, concrete objects. Classes often represent broad categories, like Car or Dog that share attributes . These classes define what attributes an instance of this type will have, like color , but not the value of those attributes for a specific object.

Classes can also contain functions called methods that are available only to objects of that type. These functions are defined within the class and perform some action helpful to that specific object type.

For example, our Car class may have a repaint method that changes the color attribute of our car. This function is only helpful to objects of type Car , so we declare it within the Car class, thus making it a method.

Class templates are used as a blueprint to create individual objects . These represent specific examples of the abstract class, like myCar or goldenRetriever . Each object can have unique values to the properties defined in the class.

For example, say we created a class, Car , to contain all the properties a car must have, color , brand , and model . We then create an instance of a Car type object, myCar to represent my specific car. We could then set the value of the properties defined in the class to describe my car without affecting other objects or the class template. We can then reuse this class to represent any number of cars.

Benefits of OOP for software engineering

  • OOP models complex things as reproducible, simple structures
  • Reusable, OOP objects can be used across programs
  • Polymorphism allows for class-specific behavior
  • Easier to debug, classes often contain all applicable information to them
  • Securely protects sensitive information through encapsulation

How to structure OOP programs

Let’s take a real-world problem and conceptually design an OOP software program.

Imagine running a dog-sitting camp with hundreds of pets where you keep track of the names, ages, and days attended for each pet.

How would you design simple, reusable software to model the dogs?

With hundreds of dogs, it would be inefficient to write unique entries for each dog because you would be writing a lot of redundant code. Below we see what that might look like with objects rufus and fluffy .

As you can see above, there is a lot of duplicated code between both objects. The age() function appears in each object. Since we want the same information for each dog, we can use objects and classes instead.

Grouping related information together to form a class structure makes the code shorter and easier to maintain.

In the dogsitting example, here’s how a programmer could think about organizing an OOP:

  • Create a class for all dogs as a blueprint of information and behaviors (methods) that all dogs will have, regardless of type. This is also known as the parent class .
  • Create subclasses to represent different subcategories of dogs under the main blueprint. These are also referred to as child classes .
  • Add unique attributes and behaviors to the child classes to represent differences
  • Create objects from the child class that represent dogs within that subgroup

The diagram below represents how to design an OOP program by grouping the related data and behaviors together to form a simple template and then creating subgroups for specialized data and behavior.

The Dog class is a generic template containing only the structure of data and behaviors common to all dogs as attributes.

We then create two child classes of Dog , HerdingDog and TrackingDog . These have the inherited behaviors of Dog ( bark() ) but also behavior unique to dogs of that subtype.

Finally, we create objects of the HerdingDog type to represent the individual dogs Fluffy and Maisel .

We can also create objects like Rufus that fit under the broad class of Dog but do not fit under either HerdingDog or TrackingDog .

Next, we’ll take a deeper look at each of the fundamental building blocks of an OOP program used above:

In a nutshell, classes are essentially user-defined data types . Classes are where we create a blueprint for the structure of methods and attributes. Individual objects are instantiated from this blueprint.

Classes contain fields for attributes and methods for behaviors. In our Dog class example, attributes include name & birthday , while methods include bark() and updateAttendance() .

Here’s a code snippet demonstrating how to program a Dog class using the JavaScript language.

Remember, the class is a template for modeling a dog, and an object is instantiated from the class representing an individual real-world item.

Enjoying the article? Scroll down to sign up for our free, bi-monthly newsletter.

Objects are, unsurprisingly, a huge part of OOP! Objects are instances of a class created with specific data. For example, in the code snippet below, Rufus is an instance of the Dog class.

When the new class Dog is called:

  • A new object is created named rufus
  • The constructor runs name & birthday arguments, and assigns values
Programming vocabulary: In JavaScript, objects are a type of variable. This may cause confusion because objects can be declared without a class template in JavaScript, as shown at the beginning. Objects have states and behaviors. The state of an object is defined by data: things like names, birthdates, and other information you’d want to store about a dog. Behaviors are methods the object can undertake.
N/A What is it? Information Contained Actions Example
Classes Blueprint Attributes Behaviors defined through methods Dog Template
Objects Instance State, Data Methods Rufus, Fluffy

Attributes are the information that is stored. Attributes are defined in the Class template. When objects are instantiated, individual objects contain data stored in the Attributes field.

The state of an object is defined by the data in the object’s attributes fields. For example, a puppy and a dog might be treated differently at a pet camp. The birthday could define the state of an object and allow the software to handle dogs of different ages differently.

Methods represent behaviors. Methods perform actions; methods might return information about an object or update an object’s data. The method’s code is defined in the class definition.

When individual objects are instantiated, these objects can call the methods defined in the class. In the code snippet below, the bark method is defined in the Dog class, and the bark() method is called on the Rufus object.

Methods often modify, update or delete data. Methods don’t have to update data though. For example, the bark() method doesn’t update any data because barking doesn’t modify any of the attributes of the Dog class: name or birthday .

The updateAttendance() method adds a day the Dog attended the pet-sitting camp. The attendance attribute is important to keep track of for billing Owners at the end of the month.

Methods are how programmers promote reusability and keep functionality encapsulated inside an object. This reusability is a great benefit when debugging. If there’s an error, there’s only one place to find it and fix it instead of many.

The underscore in _attendance denotes that the variable is protected and shouldn’t be modified directly. The updateAttendance() method changes _attendance .

Four Principles of OOP

The four pillars of object-oriented programming are:

  • Inheritance: child classes inherit data and behaviors from the parent class
  • Encapsulation: containing information in an object, exposing only selected information
  • Abstraction: only exposing high-level public methods for accessing an object
  • Polymorphism: many methods can do the same task

Inheritance

Inheritance allows classes to inherit features of other classes. Put another way, parent classes extend attributes and behaviors to child classes. Inheritance supports reusability .

If basic attributes and behaviors are defined in a parent class, child classes can be created, extending the functionality of the parent class and adding additional attributes and behaviors.

For example, herding dogs have the unique ability to herd animals. In other words, all herding dogs are dogs, but not all dogs are herding dogs. We represent this difference by creating a child class HerdingDog from the parent class Dog , and then adding the unique herd() behavior.

The benefits of inheritance are programs can create a generic parent class and then create more specific child classes as needed. This simplifies programming because instead of recreating the structure of the Dog class multiple times, child classes automatically gain access to functionalities within their parent class.

In the following code snippet, child class HerdingDog inherits the method bark from the parent class Dog , and the child class adds an additional method, herd() .

Notice that the HerdingDog class does not have a copy of the bark() method. It inherits the bark() method defined in the parent Dog class.

When the code calls fluffy.bark() method, the bark() method walks up the chain of child to parent classes to find where the bark method is defined.

Note: Parent classes are also known as superclasses or base classes. The child class can also be called a subclass, derived class, or extended class.

In JavaScript, inheritance is also known as prototyping . A prototype object is a template for another object to inherit properties and behaviors. There can be multiple prototype object templates, creating a prototype chain.

This is the same concept as the parent/child inheritance. Inheritance is from parent to child. In our example, all three dogs can bark, but only Maisel and Fluffy can herd.

The herd() method is defined in the child HerdingDog class, so the two objects, Maisel and Fluffy , instantiated from the HerdingDog class have access to the herd() method.

Rufus is an object instantiated from the parent class Dog , so Rufus only has access to the bark() method.

Object Instantiated from Class Parent Class Methods
Rufus Dog N/A bark()
Maisel Herding Dog Dog bark(), herd()
Fluffy Herding Dog Dog bark(), herd()

Encapsulation

Encapsulation means containing all important information inside an object , and only exposing selected information to the outside world. Attributes and behaviors are defined by code inside the class template.

Then, when an object is instantiated from the class, the data and methods are encapsulated in that object. Encapsulation hides the internal software code implementation inside a class and hides the internal data of inside objects.

Encapsulation requires defining some fields as private and some as public.

  • Private/ Internal interface: methods and properties accessible from other methods of the same class.
  • Public / External Interface: methods and properties accessible from outside the class.

Let’s use a car as a metaphor for encapsulation. The information the car shares with the outside world, using blinkers to indicate turns, are public interfaces. In contrast, the engine is hidden under the hood.

It’s a private, internal interface. When you’re driving a car down the road, other drivers require information to make decisions, like whether you’re turning left or right. However, exposing internal, private data like the engine temperature would confuse other drivers.

widget

Method Overriding

Runtime polymorphism uses method overriding. In method overriding, a child class can implement differently than its parent class. In our dog example, we may want to give TrackingDog a specific type of bark different than the generic dog class.

Method overriding could create a bark() method in the child class that overrides the bark() method in the parent Dog class.

Method Overloading

Compile Time polymorphism uses method overloading. Methods or functions may have the same name but a different number of parameters passed into the method call. Different results may occur depending on the number of parameters passed in.

In this code example, if no parameters are passed into the updateAttendance() method. One day is added to the count. If a parameter is passed in updateAttendance(4) , then 4 is passed into the x parameter in updateAttendance(x) , and 4 days are added to the count.

The benefits of Polymorphism are:

  • Objects of different types can be passed through the same interface
  • Method overriding
  • Method overloading

Object-oriented programming requires thinking about the structure of the program and planning out an object-oriented design before you start coding. OOP in computer programming focuses on how to break up the requirements into simple, reusable classes that can be used to blueprint instances of objects. Overall, implementing OOP allows for better data structures and reusability, saving time in the long run.

If you’d like to take a deep dive into OOP, Educative has courses for OOP in:

These courses are text-based with in-browser coding environments, so you can learn even faster and more efficiently. No setup is required; get in and start coding!

Happy learning!

Continue reading about Object Oriented Programming

  • S.O.L.I.D. Principles of Object-Oriented Programming in C#
  • Exploring object-oriented programming concepts with Java
  • How to Use Object-Oriented Programming in Python

Haven’t found what you were looking for? Contact Us

What are the 4 basic principles of OOP?

The four main theoretical principles of object-oriented programming (OOP) are: Abstraction, encapsulation, polymorphism and inheritance.

Why is OOP useful?

Object-oriented programming (OOP) makes it easy for developers to group code into small and reusable parts. It also helps developers organize the code so that it can be modified easily.

What are the advantages and disadvantages of Object-Oriented Programming?

Object-Oriented Programming (OOP) offers significant benefits by enabling the development of reusable, modular code and the efficient modeling of complex systems through abstraction and encapsulation. However, OOP also has some drawbacks such as increased complexity in design and understanding, and potential for memory overhead due to object instantiation.

Why do you need OOP?

Object-oriented programming (OOP) offers numerous benefits compared to procedural programming: It is more efficient and simpler to implement. OOP delivers a well-defined structure for programs. It aids in keeping the code concise and nonrepetitive, in line with the “Don’t Repeat Yourself” (DRY) principle. It, therefore, makes it easier to maintain, modify, and debug the code.

Why is Object-oriented programming useful?

Object-oriented programming (OOP) can be very beneficial in making code more efficient and easy to understand. OOP organizes code into reusable objects that encapsulate data and behavior, making it easier to manage and understand complex systems.

Learn in-demand tech skills in half the time

Mock Interview

Skill Paths

Assessments

Learn to Code

Tech Interview Prep

Generative AI

Data Science

Machine Learning

GitHub Students Scholarship

Early Access Courses

For Individuals

Try for Free

Gift a Subscription

Become an Author

Become an Affiliate

Earn Referral Credits

Cheatsheets

Frequently Asked Questions

Privacy Policy

Cookie Policy

Terms of Service

Business Terms of Service

Data Processing Agreement

Copyright © 2024 Educative, Inc. All rights reserved.

Browse Course Material

Course info, instructors.

  • Adam Marcus

Departments

  • Electrical Engineering and Computer Science

As Taught In

  • Programming Languages
  • Software Design and Engineering

Learning Resource Types

Introduction to programming in java, lecture 4: classes and objects.

Lecture presentation on programming in Java. Topics include: object oriented programming, defining classes, using classes, constructors, methods, accessing fields, primitives versus references, references versus values, and static types and methods.

facebook

You are leaving MIT OpenCourseWare

Lectures and Slides

For use with the book, introduction to object oriented programming, timothy a. budd, addison-wesley longman , 1997, viewing this material, permission for use.

IMAGES

  1. Object Oriented Programming Ppt Powerpoint Presentation Ideas Guidelines Cpb

    presentation on object oriented programming

  2. PPT

    presentation on object oriented programming

  3. PPT

    presentation on object oriented programming

  4. PPT

    presentation on object oriented programming

  5. PPT

    presentation on object oriented programming

  6. PPT

    presentation on object oriented programming

VIDEO

  1. Week 13

  2. Introduction to Object Oriented Programming System

  3. OOP: Introduction to Object Oriented Programming Paradigm

  4. Object Oriented Programming L2

  5. OBJECT ORIENTED PROGRAMMING (GİRİŞ )

  6. Object Oriented Programming Important Topics For Paper

COMMENTS

  1. Object Oriented Programming_combined.ppt - Google Slides

    Introduction to OOP. Why use OOP? Object Oriented Programming (OOP) is one of the most widely used programming paradigm. Why is it extensively used? Well suited for building trivial and...

  2. Introduction to Object Oriented Programming | PPT - SlideShare

    Simula is considered the first object-oriented 14 programming language. • Simula was designed for doing simulations, and the needs of that domain provided the framework for many of the features of object-oriented languages today.

  3. OOP PPT 1.pptx - Google Slides

    An object-oriented program consists of a set of objects that communicate with each other. The process of programming in an object-oriented language, involves the following basic steps:...

  4. Object Oriented Programming | PPT - SlideShare

    This document provides an overview of basic object-oriented programming (OOP) concepts including objects, classes, inheritance, polymorphism, encapsulation, and data abstraction. It defines objects as entities with both data (characteristics) and behavior (operations).

  5. CS106B Object-Oriented Programming - Stanford University

    CS 106B: Programming Abstractions. Summer 2020, Stanford University Computer Science Department. Lecturers: Nick Bowman and Kylie Jue. For every lecture, we will post the lecture slides and any example code that will be used during lecture, usually in advance of the beginning of the lecture.

  6. Introduction to oops concepts | PPT - SlideShare

    An overview of object oriented programming including the differences between OOP and the traditional structural approach, definitions of class and objects, and an easy coding example in C++. This presentation includes visual aids to make the concepts easier to understand. Read more. 1 of 50.

  7. MIT6 0001F16 Object Oriented Programming - MIT OpenCourseWare

    OBJECT ORIENTED PROGRAMMING. (download slides and .py files ĂŶĚ follow along!) 6.0001 LECTURE 8. 1. OBJECTS. Python supports many different kinds of data. 1234 3.14159 "Hello" [1, 5, 7, 11, 13] {"CA": "California", "MA": "Massachusetts"} each is an object, and every object has: a type. an internal data representation.

  8. What is object-oriented programming (OOP)? Explained in depth

    Object-oriented programming (OOP) is a fundamental programming paradigm used by nearly every developer at some point in their career. OOP is the most popular programming paradigm used for software development and is taught as the standard way to code for most of a programmer’s educational career.

  9. Lecture 4: Classes and Objects | Introduction to Programming ...

    Lecture presentation on programming in Java. Topics include: object oriented programming, defining classes, using classes, constructors, methods, accessing fields, primitives versus references, references versus values, and static types and methods.

  10. Chapter Slides - Oregon State University College of Engineering

    Introduction to Object Oriented Programming. Timothy A. Budd. published by. Addison-Wesley Longman, 1997. Directory. Part 1: Thinking in the Object Oriented Way. Chapter 1: Thinking Object-Oriented. Chapter 2: Object-Oriented Design. Part 2: Classes, Methods and Messages. Chapter 3: Classes and Methods.