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

16

u/tube32 Apr 05 '22
  1. Constructors and why are they important.

  2. Same about setters and getters. What's the point of declaring a variable private only to allowed to access them via public methods?

  3. Dependency injection

2

u/Longjumping_Round_46 Apr 05 '22

I don't know how much you know about OOP, so I'll try to keep it simple.

Say you have a class that represents a real world object.

public class Person
{ 

}

Classes can have data members and functions.

public class Person
{ 
    public string name;

    public int birthYear;

    public void IntroduceYourself()
    {
        Console.WriteLine("Hi, my name is {name}, and I was born in {birthYear}");
    }
}

With constructors, when you create (instantiate) a new class, you can set the date members right then and there.

public class Person
{ 
    public string name;

    public int birthYear;

    public void IntroduceYourself()
    {
        Console.WriteLine("Hi, my name is {name}, and I was born in {birthYear}");
    }

    public Person(string name, int birthYear)
    {
        this.name = name;
        this.birthYear = birthYear
    }
}

And when you want to create a class:

Person terry = new Person("Sir Terry Pratchett", 1948); 

terry.IntroduceYourself();