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

Show parent comments

2

u/Coding_Cactus Apr 05 '22

Here's a link to a comment I made a while back on OOP

I'll try to make a shorter one here if you don't want to read that one.

Take this string:

string aSampleString = "Test12345";

If you wanted to know the length of that string how would you do it?

SampleString.length();

Ok, easy, but what if we made a new string?

string aTotallyDifferentString = "LoremIpsum"

Well, we'd do the same exact thing.

aTotallyDifferentString.length();

The reason is because a string in Java is a class. To not add too much, it's a collection of properties and methods that can be inherited so that you don't have the same method typed out a thousand times and also to ensure that the underlyfing functionality doesn't deviate.

Then take that and apply it to totally made up class.

class FingerGun
{
    string Shoot() {
        return "Bang!"
    }
}

Now, what do you think is gonna happen if I make two new classes from that one?

class LeftHand extends FingerGun
{
    public string HandName = "Left";
}

class RightHand extends FingerGun
{
    public string HandName = "Right";
}

/*This is just an example, ignore the horrid syntax mistakes*/

LeftHand Lefty = new LeftHand();
RightHand Right = new RightHand();

Based on the above example, this should do exactly what you expect it to:

Lefty.Shoot();
Righty.Shoot();

They both extend from FingerGun so they both have the Shoot() method. No need to re-create it on both of them unless they need to function differently from there.

2

u/[deleted] Apr 06 '22

thank you so much man! this really helps me understand the meaning and why we even use oop!