+ 2
Why i can't put private in the place of public
first of all i am a new learner. when i start to write a java program. i have to write like that class class name { public static void main( string [ ] args) then etc. etc. so if i put private in the place of public it says me to write public in there. why is that happening. why i cant put private in the place of public. plz explain me with easy words. i am not so much good in english. if anyone here who knows bangla language plz explain me in bangla. thank u.
4 Answers
+ 3
The main function/loop is your entry point into the program; it's how it starts up and runs. If you make that function/loop private, then the OS can't access that function, which means that it cannot start your program. As such, the main function needs to be public so it's seen by the OS.
As an example of when to use private, classes are a great example of such. Often we'll hide away the members of a class (encapsulation) to prevent them from being accessed via other portions of the code. In that instance, we utilize SETTER/GETTER methods in order to interact with the objects created from the class. This is also much more secure than leaving everything open for the world to see.
Example:
private int num;
public int getNum(){
return this.num;
}
public void setNum(int num){
this.num = num;
}
+ 10
it is strictly follow the signature
if not find the following signature then runtime error will be generated
//for more information
https://www.allinterview.com/showanswers/131747/1-if-use-private-place-public-static-void-main-2-int-3-ommit-keyword-from-statem.html
https://stackoverflow.com/questions/6477232/why-is-it-mandatory-to-declare-main-method-public-why-it-is-not-possible-for-j?rq=1
+ 10
when U don't want to allow other class & their objects to access that method
//for more information
http://javarevisited.blogspot.in/2012/03/private-in-java-why-should-you-always.html?m=1
+ 2
so when i should use private