This site requires JavaScript, please enable it in your browser!
Greenfoot back
jdemshki
jdemshki wrote ...

2011/12/20

Private void vs. public void

jdemshki jdemshki

2011/12/20

#
I've been watching videos and doing tutorials but i still don't understand the difference between these two things. Can anyone help?
Builderboy2005 Builderboy2005

2011/12/20

#
Both create a void method (a method that does not return anything) But only the public method can be accessed by other classes. The private method can only be used by the class in which it is contained. For example, if I made a Example class:
class Example{
    public void printHi(){
        printString("Helooooo");
    }
    private void printString(String str){
        System.out.println(str);
    }
}
If I created an Example object, this would be legal code:
Example e1 = new Example();
e1.printHi();
This would not be legal code:
Example e1 = new Example()
e1.printString("Heloooo");
Because we would not be calling the method 'printString' from inside the Example class. Since printHi() is public, we can call it from outside the Example class.
kiarocks kiarocks

2011/12/20

#
Is there any reason for using private? I just find it unnecessary.
Builderboy2005 Builderboy2005

2011/12/20

#
Private methods have less to do with writing games and more to do with writing API's. Since Java is build on the idea that all API's and classes should be able to work together and have easy interfaces, having Public/Private/Protected methods are an important part of that. Private methods are just ways to ensure that other people can't mess with the methods you don't want them to mess with. For example, if I was making a routine to draw a 3D object onto an image, I might make myself multiple helper methods to do things like 3D to 2D point projection. This would be helpful to me when drawing the object, but not related to the goal of my class. I would likely make these helper methods private so that when someone looks at my 3D drawing API, they would see one simple draw method, and not a whole bunch of helper methods that really are of no use to them.
kiarocks kiarocks

2011/12/20

#
Ok, what is the point of protected?
Builderboy2005 Builderboy2005

2011/12/20

#
This site has an excellent chart that shows how the different modifiers grant different types of access to different types of areas. As the chart shows, protected methods are a bit more restricted than public, as completely different classes (world) cannot access them. However, classes from the same package, or classes that extend that class are still granted access. A good example of this is our very own Greenfoot protected addedToWord(World world).
kiarocks kiarocks

2011/12/21

#
Ok, i see.
You need to login to post a reply.