r/learnprogramming • • Apr 05 '22

Name one programming/comp sci concept you never understood and if you understand it, try to explain it to them

Name a programming concept such as virtual functions, pointers, certain algorithms, etc that you always had a hard time understanding and why.

Someone else who reads yours and does understand it, try to explain it to them to help them learn

1.6k Upvotes

738 comments sorted by

View all comments

3

u/[deleted] Apr 05 '22

Object Oriented Programming (Java)

I’m pretty new to this concept and I am still trying to learn it but right now it makes absolutely no sense to me.

1

u/__Fred Apr 06 '22 edited Apr 06 '22

You know types, right? Like int and String. A class is a new custom type, that is made up out of existing types.

I started programming with a version of "Basic" that didn't have OOP.

How would you model a game where there are a couple enemies and they each have an x and a y coordinate and some health points without OOP? Like this:

int[] enemies_x;
int[] enemies_y;
int[] enemies_health;

void shoot(int x, int y) {
    for (int i=0; i<enemy_count; i++) {
        if (enemy_x[i] == x && enemy_y[i] == y) {
            enemy_health[i]--;
        }
    }
}

void moveEnemyDown(int index) {
    enemies_y[index]++;  // on screens higher y typically means down
}

You could also solve it with an array of arrays:

int[][] enemies;
// enemies[i][0]   would be the x of enemy i
// enemies[i][1]   would be the y of enemy i
// enemies[i][2]   would be the health of enemy i

With classes and objects you can refer to different properties like this:

class Enemy {
    public int x;
    public int y;
    public int health;

    public void moveDown() {
        this.y++;
    }
}

// ...

Enemy[] enemies;
// enemies[i].x   refers to the x of enemy i
// enemies[i].y   refers to the y of enemy i
// enemies[i].health   refers to the health of enemy i
// enemies[i].moveDown()  moves the enemy downwards, like in Space Invaders

You can do everything that you program with OOP also without OOP. In fact earlier compilers of the object-oriented language C++ just transformed the code to C, a language without classes. OOP is just for organizing code for humans.

That's not everything to know about classes as I haven't talked about inheritance yet, but it's a start. I think educators should show OOP code in conjunction with non-OOP code to show the advantages.