Difference between Public class and private class.

Discussion in 'iOS Programming' started by zijianz, Jun 29, 2012.

  1. zijianz macrumors newbie

    May 21, 2012
    I am watching the Stanford programming class. He first defined the class in .h file. After that he defined a 'private class' in the .m file, with the same name.

    My question is, for example, 1. what is the difference? 2. Under what kind of circumstance, shall we use instance of private class?
  2. CodeBreaker, Jun 29, 2012
    Last edited: Jun 29, 2012

    CodeBreaker macrumors 6502

    Nov 5, 2010
    Sea of Tranquility
    The class stays the same, but there are two interfaces to it -- Public and Private.

    Properties and methods in the public interface (.h file) are visible to other objects, i.e. you can use them from outside your class.

    Properties and methods in the private interface (.m file) are only visible to the class itself. You cannot use them from outside of your class.

    Say for example you have a ForumMember class. In the public implementation, you may declare properties such as nickname and location, which can be read by others.

    But you won't want to include the members UUID or his password in the public interface, because it should stay private to the member. And at the same time, a ForumMember instance needs his password and UUID to login, and hence he himself must know it. So keep it private.

    I can't think up of anything better at the moment, but things in your class that you don't want other objects to know about should be placed inside the private interface.
  3. zijianz thread starter macrumors newbie

    May 21, 2012
    Appreciate so much for your help.

    I have two more questions about properties calling by other classes.

    1. Could the private interfaces be inherited, if I have some kind of subclass under it?

    2. If I would like to use an obj as a property inside other class. Can I call the things inside the private interface?

    Thank you so much !!!
  4. CodeBreaker macrumors 6502

    Nov 5, 2010
    Sea of Tranquility
    1. No. Your subclass can only use/override what is visible in the .h file.

    2. Not sure what you mean by that. Properties inside the private interface are not treated specially by the class. But they are non-existent for the outside world.
  5. firewood macrumors 604

    Jul 29, 2003
    Silicon Valley
    There are no real private interfaces in Objective C, as you can always use the C runtime to get at any method or property you can name. It's more a naming thing for a more disciplined methodology.

Share This Page