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?
2 Antworten
+ 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
}
}
+ 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
}