Introduction to Private Access Specifier
Members marked private can't be accessed by code in any class other than the class in which the private member was declared.
The private data members and methods are not visible within subclasses and are not inherited by subclasses.
Syntax
class MyClass {
//private data members
private int balance;
//public constructor
public MyClass() { }
//public method
public void show() {}
}
Example
1. /**
2. * @(#)Test.java
3. *
4. *
5. * @author
6. * @version 1.00 2009/11/16
7. */
8.
9. class Account {
10.
11. private int number;
12. private String name;
13. private float balance;
14.
15. /**
16. * Creates a new instance of Account.
17. */
18. public Account() {
19. }
20.
21. public void setNumber(int number) {
22.
23. if (number > 0)
24. this.number = number;
25. else
26. System.out.println("Please enter valid number.");
27. }
28.
29.
30. public void setName(String name) {
31.
32. if (name != "")
33. this.name = name;
34. else
35. System.out.println("Please enter valid name.");
36. }
37.
38. public void setBalance(float balance) {
39.
40. if (balance > 0)
41. this.balance = balance;
42. else
43. System.out.println("Please enter valid balance.");
44. }
45
46 public void show() {
47
48 System.out.println("Account Information:");
49 System.out.println("Number: "+ number);
50 System.out.println("Name: "+ name);
51 System.out.println("Balance: "+ balance);
52
53 }
54.
55. }
56.
57. public class Test {
58.
59.
60. /**
61. * @param args the command line arguments
62. */
63. public static void main(String[] args) {
64. // TODO code application logic here
65.
66. Account ac = new Account();
67.
68. ac.setNumber(12345);
69. ac.setName("Yousuf Jamshed");
70. ac.setBalance((float)435.36);
71.
72.
73. ac.show();
74.
75. }
76. }
Output
Account Information:
Number: 12345
Name: Yousuf Jamshed
Balance: 435.36
When private access modifier is used, you cannot access data members and methods directly. It allows application writer to implement checks on input data so that user must provide valid data.
Following statement produces error:
ac.number = 12345;
You can’t access number data member directly because it’s private not public.
