Friday, January 27, 2012

Discussion from Class Jan. 27th

Today we covered various topics. Here are some things I want you to have taken away from lecture today.

Be curious
Don't just use emacs like a text editor. Google things like "autocomplete emacs java" and "compile emacs java". If there is something you wish emacs did, it probably does! Go and find it!

What is a Class?
A class is a definition of an Object in java. It contains information on how instances of that class should exist in java land.

What does it mean to be public vs. private?
When something is public it can be accessed by ANY other class. When something is private it may only be accessed within the class it is declared. How does this help us maintain the state of our Objects in java?

What is a Constructor?
For our purposes, you can think of a constructor as a "special" method that must return a new instance of the class that is being created. Note: If a constructor is not explicitly defined in a class, by default it will have a public constructor that takes no parameters.

Something to discuss (respond for participation credit):
What does it mean to have a private constructor? Can you do this? Would you ever do this? When and why?


What is the purpose of having a private member variable? What are the pros? Are there any cons?

Write up some coding examples to support your arguments and share them via pastebin.com links.

Have a great weekend!

Joe

P.S.
In class we were unable to get our class files to run when they were in a package. We almost had it. We were trying to run it by using the following command "java -cp /path/to/files/ GalacticDriver". However, this was not quite correct. Since GalacticDriver.java had the package declaration "edu.unm.jcollard.jan27" I needed to specify exactly which package it was in. To get the file to run from the command line you must use the following argument "java -cp /path/to/files/ edu.unm.jcollard.jan27.GalacticDriver". This tells the java virtual machine where the class file exists. This allows us to have multiple classes named GalacticDriver that exist in different packages. However, I would try to avoid this ;)


30 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. A private member variable -
    the purpose is to keep sections of your code hidden from anyone who is not the author of the code, this is to keep unwanted eyes from seeing and changing code.
    Pros-
    keeping code out of public eye allows the feeling of safety like a nice warm blanket that your code can lay in
    Cons-
    the issue we run into with private members is sometimes we block our selves from seeing the code when we move to a different class and need to access the data member and because it is private the class even within the same package cannot see it (I think I might be wrong)

    I am sure there is much more to this but that is what I know.

    hope everyone will add to this and take advantage of the blog this is a great idea for help with the class and a solid resource to gain the knowledge of not only the teacher but the TA's and of course my fellow students

    ReplyDelete
    Replies
    1. Sorry Derek, but your answer is WAY off. Declaring a variable as private does NOT "keep unwanted eyes from seeing and changing code."

      Anyone else want to answer?

      By the way, if you are having trouble posting comments, please send me email about it right away.

      Delete
    2. Derek, this is a nice try and it has some correctness to it. If you don't give anyone your code, they can't change it. However, this can be said even if you mark your variables public.

      Instead, you might just give someone the .class file that is generated. As it turns out, you can still use .class files without the source!

      Try it out! Compile the Creature.java file in the repository and then copy the .class file to another directory. Now, write a simple class in the same directory (the default package) and see what you can do with it.

      Also, I don't think your con is justified. I think what you mean is "we can't access private members in other classes". Is this really a bad thing? How can we get around this? Think back to class to how we modified the private member name in the CelestialBody.

      Joe

      Delete
  3. ok so i guess my next question is are private members inherited? this leads to the talk of sub-classes and super-classes. if you were to create a private member inside the super-class you would have to use an accessor method (getters) for the private member to be used in the sub-class. its values are inaccessible unless you use accessor method, is used correct? taking one step at a time making sure i understand what it does before i can see pro and cons

    ReplyDelete
    Replies
    1. Yes. Private members are inherited. However, you do not have direct access to them in the subclass.

      This is going a little ahead in the class. You should be able to see good reasons to have private member variables even if the class does not extend another.

      It is possible to see and modify a private member variable. You just don't have direct access. How might someone allow access to a private variable? Think back to the example of the CelestialBody class.

      Delete
  4. I think purpose of having a private constructor would be to not allow people to create another instance of your class in any other class. I've also heard creating private constructors can be useful for making singletons. I am not exactly sure what a singleton is, but from my understanding is that it is a class where an object has been instantiated only once. I think this would be useful if you wanted to create an object to represent a sun in a program that deals with a solar system, cause you only want one sun, and don't want anybody to be able to create more than one sun.

    I think the purpose of having private member variables is so you can have a variable that can be accessed by various methods in your class, and that cannot be easily reassigned in another by simply saying it equals something. The pros I guess are that you have variable that can be accessed throughout the class and not accidentally altered in a different class. The only con if it is even considered a con that I can think of is that if you want to change the value of a private member variable in another class, you have to create "setter" and "getter" methods within the original class, which is a little more work.

    ReplyDelete
    Replies
    1. This is a good start. If a constructor is private, that means you can only create an instance of that class from within that class. Does this mean that no one can get instances of that class? You mention that it is good for making singletons. This is true. However, how does someone access the singleton if the constructor is private?

      You are also correct that a private member variables can be accessed by methods in that class. Again, you are correct that it can not be easily reassigned. I think your pro can be justified, the only time the variable can be changed is from within the class. This means whoever is writing the class has full* control over how that variable is assigned.

      I don't think you believe your own con and I don't either. Isn't that a pro? The users of your class *must* adhere to your provided methods. This means they can only set the variable to values that you think are acceptable for that variable.

      I put a * by full earlier because it is a little bit of a lie. It is merely a gentleman's agreement that you won't modify this value without using the provided interface (methods) to do so. There are mechanics of Java that we may or may not go over that allows us to see and modify all members of a class.

      Delete
  5. Private Constructor Pros:

    - a private constructor with no args disables caller's ability to create object(s) and access the default constructor. Useful if class has static methods which do stuff to data passed to them and not data stored in the class.

    - can intercept caller's construction args and manipulate them as desired. (overload constructor and provide a public interface which actually calls an internal private constructor). Using Celestial Bodies as an example, the constructor could check the format of the name string and then internally create the object.

    Private Constructor Cons:

    -nothing that can't be worked around. See the protected access modifier, http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

    Unrelated:

    Are the timestamps calculated from the wrong timezone or do you (Tom and Joe) really reply to our posts before 6:00am? I can't decide whether that's impressive or insane!

    ReplyDelete
    Replies
    1. Good reply Rob. However, I'm not convinced.

      You say by having a private constructor you disable the caller's ability to create object(s). This is not necessarily true. It prevents people from accessing the constructor directly (from outside of the class). How could you have a private constructor and still produce instances of that class (from outside of the class)?

      You state, "Useful if class has static methods which do stuff to data passed to them and not data stored in the class." This is true. For example you can't create a new instance of the Math, Arrays, or Collections classes directly by typing "new Math, new Arrays, or new Collections". If you look into these classes they provided a bunch of utility methods.

      You say that a private constructor "can intercept caller's construction args and manipulate them as desired." Yes it can. But so can any other type of constructor. Again, I ask using only private constructors, how can you give access to users to create instances of your class?

      Finally, your "no" cons is not justified in my opinion. You say that there is nothing that can be worked around and then you give an example to use a protected modifier. Which is actually not private. It turns our if you use protected, that method, constructor, or variable can be accessed by any other class in the same package (not just sub classes).

      Also, the time stamps show up based on the current time zone in your google account. Finally, yes my reply was at 6AM. I don't require sleep like normal humans ;)

      Delete
  6. Regarding "no cons" and "worked around", I meant to imply that at a higher design level, a class which needs to be accessible to sub classes and/or other classes in its package can be defined with access modifiers other than private, such as protected or default (no modifier), to "work around" the limitations imposed (on a class) by a private constructor.

    Also, the link in my previous post has some concise information on the different modifiers, should anyone be interested.

    ReplyDelete
    Replies
    1. Sure, but then you are no longer using the private modifier.

      Delete
  7. For a private constructor: if people can access your code, wouldn't you want them to be able to access the constructors as well? That's why it's there right? Unless creating another instance of your code without running the whole class is something that will make it crash.
    For a private member: this might be when you have a variable that is running tabs on something like coordinates of where a graphic is and you don't want someone to mess with that since it could mess up what it is you are drawing or mess up where the picture is supposed to be, like a picture on the background of a website. If you don't want someone messing with your variables and possible causing glitches, you would want private members.

    ReplyDelete
    Replies
    1. Obviously, if you wanted to allow people to use your constructor, you would not want to make it private. However, there are reasons you might make the constructor private. 1 that has been mentioned is to make it so you can not create instances of that class. A prime example of this is the Math class. You can not create instances of it and it only contains static utility methods.

      A question to the class at this point is, how might you provide members access to an instance or instances of your class without providing a non-private constructor?

      You are correct about private member variables. If you don't want the outside world mucking up your internal data don't let them. Instead, you provide an interface that you have control over. For example, maybe you have an accelerate() method that causes your private velocity variable to increase. By requiring the user of your class to use the accelerate() method you can determine how much it accelerates.

      Delete
    2. Dean Dominguez (using his wife's account because he's too lazy to make his own):

      Could you make a method in your class that allows you get an instance of the class? A get instance method, that returns an instance.

      Delete
  8. That's correct. You could create a method that returns an instance of that class rather than a constructor. But, isn't that what a constructor is for? What are the benefits of doing this?

    ReplyDelete
    Replies
    1. I think you could essentially use a method like what you've described as a way to easily create instances of the class that diverge from the default settings in some systematic way.

      http://pastebin.com/RmmMiWNJ

      Delete
    2. Stav, why couldn't you do this with a constructor?

      What is special about a constructor?

      Imagine you want to create a class that stores coordinates specifically for a display that only allows positive int values for coordinates.

      What advantages would you have by using a static method?
      What disadvantages would you have by using a static method?

      Delete
    3. In the case of the display coordinates, using a static method could be useful if multiple classes were using it for the same display, because each time a static method is called, it is the same for all. If a static variable is changed, it is changed for everything that calls it from then on. However, the disadvantage is that you could not have different values for different instances, like if you had multiple displays that your program is being used for.

      Delete
    4. Ronald, I think you might be confused.

      A static method can return anything, it does not have to return a static member variable.

      When a method is marked static it is accessible by the class rather than by an instance of the class.

      Does that make sense?

      Delete
    5. Yes, actually, perfect sense. I was fairly confused on the difference between a static method and a static variable. Thanks.

      Delete
  9. From my experience, a private constructor forces the user to call a method to either manipulate or change the variable from outside the class. I believe that this is a sort of catch, making sure that the programmer truly wants to change said variable.

    I also heard Mr. Hayes say something about bug-catching. If you are sure that a certain class works, and somebody else develops another class that interacts with your class but doesn't work, then you know that the bug is in the new class. Did that make any sense? If not, I'll try to clarify.

    ReplyDelete
    Replies
    1. Jennifer, let's be careful we understand each term. Constructor is what you use to create an instance of an Object. A method has nothing to do with a constructor.

      I think you mean to say a private member variable instead of constructor.

      Basically, having a private member creates a contract between you and whoever is going to use your class that says, "You will adhere to the interface I have provided for modifying this variable."

      As far as bug catching goes, it is very helpful if you know what legal values your variables can contain. By enforcing someone to use your setNumber() method you can ensure that they only ever set your number according to some interface.

      For example, if you want to write a class that stores an X, Y coordinate but you only want to allow positive values, you can provide a method that checks and makes sure the values are positive. If they are not, you can decide how to handle it. In other sections of your code, you can now be sure that the values of X and Y will always be positive.

      Make sense?

      Delete
    2. Oops, that's right. I'm not used to all the vocabulary. But yeah, that's basically what I meant.

      Delete
  10. Reading the Tutorial on 'Controlling Access to Members of a Class' has helped better understand the what we discussed in lecture.

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. So if the main purpose of making a constructor private is to enforce your control of how the contructor is called, what are the cons of doing this?

    It seems to me that by doing this, I would only be making my code more secure.

    ReplyDelete
    Replies
    1. I certainly would agree with this idea for private member variables. However, by making a constructor private you make it inaccessible to any sub-classes.

      What would it mean if a sub-class can not access any of the super classes constructors?

      Delete
    2. The sub-classes wouldn't be able to inherit or access the fields and methods of the constructor, correct? I can see how this could really hinder the way you would write your code.

      Delete