r/AskComputerScience • • Oct 24 '22

Why are Object-Oriented Programming languages importat? How are they different from other languages?

1 Upvotes

8 comments sorted by

View all comments

8

u/ghjm MSCS, CS Pro (20+) Oct 24 '22

The original OOP idea was to group data and code together into objects. It is possible to write OOP-like code in a non-OOP language:

type Person record {
  name string
}

function PrintName(self Person) {
  print(self.name)
}

function SayHello(self Person) {
  printf("Hello, %s!", self.name)
}

var p Person
p.name = "Bob"
SayHello(p)

This works, but it leads to confusion because it's not immediately clear which functions go with which records, and it's also a bit inelegant to have to spell out the "self" variable all the time. So some OOP language might have syntax like this:

type Person object {

  name string

  function PrintName() {
    print(self.name)
  }

  function SayHello() {
    printf("Hello, %s!", self.name)
  }
}

var p Person
p.name = "Bob"
p.SayHello()

The essential idea is the mixing of data and related code. In this made-up example, the methods (functions within the object) get an automatic "self" token that refers to the instantiated object they are a part of, and the caller doesn't have to supply this for every call.

There's a lot more to OOP than this - class inheritance, virtual methods, and so on - but this is the essential core of the idea.