0

Java: private and public

So i'm learning java and i have a question, because i think I understand everything else pretty good: what is the difference between public and private?

1st May 2019, 5:20 PM
Laurenz baumgartner
Laurenz baumgartner - avatar
2 Réponses
+ 5
class A{ static private int x; static public int y; } class Program{ public static void main(String[] args) { System.out.print (A.x) ; //Compile time error System.out.print (A.y) ; // no error } } You can't access private variables from outside the class where they are defined. Private variables and methods can only be used in class A. It's a good practice to make variables private. Get methods (getters) are used to access private variables from outside of the class. Here's an example : class A{ static private int x; static int getX() { return x; } } class Program{ public static void main(String[] args) { System.out.print (A.getX()) ; // output 0 } }
1st May 2019, 5:38 PM
voja
voja - avatar
+ 3
public means other classes have access. private means only the current class have access. For example: Class A{ private int x; //some code } Class B{ A test = new A(); test.x = 4 --> not possible } private Class A{ } Class B{ A test = new A(); --> not possible because class A is private }
1st May 2019, 5:41 PM
Denise Roßberg
Denise Roßberg - avatar