What is the difference between public, private, and protected?

后端 未结 17 1586
抹茶落季
抹茶落季 2020-11-21 07:54

When and why should I use public, private, and protected functions and variables inside a class? What is the difference between them?<

17条回答
  •  情深已故
    2020-11-21 08:09

    Reviving an old question, but I think a really good way to think of this is in terms of the API that you are defining.

    • public - Everything marked public is part of the API that anyone using your class/interface/other will use and rely on.

    • protected - Don't be fooled, this is also part of the API! People can subclass, extend your code and use anything marked protected.

    • private - Private properties and methods can be changed as much as you like. No one else can use these. These are the only things you can change without making breaking changes.

    Or in Semver terms:

    • Changes to anything public or protected should be considered MAJOR changes.

    • Anything new public or protected should be (at least) MINOR

    • Only new/changes to anything private can be PATCH

    So in terms of maintaining code, its good to be careful about what things you make public or protected because these are the things you are promising to your users.

提交回复
热议问题