1

Private is a access specifier. It means that anything say a instance private declared private cannot be accessed by methods of another class.

What is the point of being private if it can be changed by public methods.

Maybe it is because either because my book's poor explanation or my understanding problem that I just don't get what private is.

The book says that being private is a process of hiding the data and providing methods for data access. (Encapsulation)

Also, here is a example where a error would occur. But I have no idea what is it:

public class BankRobber
{
BandAccount momSavings =           
new BankAccount (1000);

...
momSaving.balance = -1000;
}}

A

1 Answers1

3

The point of "private" is not to make it impossible for other classes to access the member, but to make it impossible for other classes to access the member except in ways that are allowed by the public (or protected) methods.

Shanqing Cai
  • 3,756
  • 3
  • 23
  • 36
  • Ok, based on what you said, what is wrong with the code in the question? – most venerable sir Mar 14 '15 at 20:12
  • First of all, what language is the code? Second, what is the error message that you got? My guess is that it is Java and the error is that "balance" is a private member of the class BankAccount that shouldn't be accessed directly as in your code sample. – Shanqing Cai Mar 14 '15 at 20:14
  • This is Java. No the code is not mine, I got it from a book. momSavings.balance is the balance field of the object momSaving. This line look strange, cause I have never seen any thing ending in .balance. The error is in this line. – most venerable sir Mar 14 '15 at 20:19
  • The line looks to me like it is declaring a instance field. But the object has already been constructed with initial balance of 1000. How can the balance be altered? – most venerable sir Mar 14 '15 at 20:20
  • When we say "class"? Is it as in String class, or as in class definition? – most venerable sir Mar 14 '15 at 20:37