Hey there, I'm trying to call a method in a subclass, savingsaccount. when i call this method, it involves a field called balance in the superclass, called account. When i try to involve this field in the method, it says that the field is private and cannot be accessed. Is there a way around this with keeping the field private? We are not supposed to change the access type.
Kind regards and much appreciation for any help
No. The superclass should provide appropriate methods to access the field's value appropriately, possibly performing validation.
The whole point of making a field private is to stop other classes from accessing it directly - instead they have to go through the methods you expose.
Add a protected getter method in the superclass to return the balance value, such as this:
protected double getBalance() {
return this.balance;
}
This method will be visible to subclasses but not visible externally. It allows you also to keep the balance field private.
If it's private you can't get at it, that's it. The author of the superclass has the responsibility to make their class open to extension. If they chose not to allow this kind of extension then there's nothing to be done.
Now check, did they provide accessor methods, or anticipate your need for extension in some other way? If you can talk to the author ask them whether they considered this need.
private means that the variable is private to that class. protected would mean that subclasses can access it and public means anyone can see it. If you can't change the access type then you should provide an accessor method in the super-class:
public double getBalance() {
return balance;
}
In the sublclass you can then see the balance by calling getBalance
use reflection.
hey, I'm just answering the question as is.
Related
This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 6 years ago.
I know this is very basic but I want to know why we should use private variable in encapsulation.I am mentioning my code. so I can give you better explanation.
Class Employee
{
private String eName;
public String getEname()
{
return this.eName;
}
public void setEname(String name)
{
this.eName=name;
}
Here "eName" is private so we can restrict outside object to access directly. variable can be access using its getter setter only.
Now my question is why we should use getter setter method? can't we declare variable as a public.?
Using setter method any one can change the value so what is need of this private variable?
Another Question
we set create read/write only method if we don't create getter method then it become write only and if we don't create setter method then it become read only.
so what is the use of read only and write only ?
If we don't create setter method then how value will set to variable ?
If we don't create getter method then how value will retrieve?
Please give me the answer of above simple questions.
Thank you
:)
The point of making variable private and
Let's say your bankBalance is a private variable and checkBalance() is a public method which is calling a public getter method getbankBalance() for bankBalance.
Now by doing this I can call checkBalance() which will call getbankBalance() function and read the value of bankBalance. I will only have read only access to sensitive data via a public method only.
Now, If the variable bankBalance is public any function can access and change the value of your bank balance, I can check for packageName.ClassName.bankBalance variable and then I can change the value of that variable to 0.
In order to provide read/write only accesses we need to make variables private, protected.
Hence The need of private variables in public methods.
Hope this is good explanation.
If we declare the method as public, then others can change its value. Sometimes, in encapsulation, you don't want the value to be changed, but only to be seen. public members can be read, as well as be changed. Hence, you declare it private.
so what is the use of read only and write only ?
I have rarely seen write only, but read only is common, for example, in bank account softwares. You want the account balance to be read, but not to be changed!
If we don't create setter method then how value will set to variable ?
obj.eName = "Whatever";
If we don't create getter method then how value will retrieve?
whatever = obj.eName;
in setter we can validate input data being set to property and take action accordingly, refer below :
public void setEname(String name)
{
//Here we can validate input data or even throw an exception
if(name!=null && name.length()<5){
this.eName="Some Default Value";
//throw new IllegalArgumentException("Your custom message goes here");
}else{
this.eName=name;
}
}
Also many api's use java reflection to set private property values, for this setter methods are required.
Now my question is why we should use getter setter method? can't we
declare variable as a public.?
Using setter method any one can change the value so what is need of
this private variable?
The public and protected methods of your classes form part of its exported API, i.e. the contract you make with client users of your class that specifies what your class does. In other words, the accessible methods specify your class's behavior.
The fields of yout class form its state. A class's state need not, and often does not, have a dependency on its contract. In other words, the fields in your class that are hidden away form part of your class's implementation (but not its behavior or its contract).
Note that the hidden parts of an implementation are not part of the contract and are also not part of the exported API. This means that you are free to change the implementation at any time without risk of breaking your client's programs as long as the implementation continues to obey the contract of your exported API. Therefore, fields that make up the state of your objects should nearly always be made private or package-private.
All this changes when you make your fields public. In this case, clients have direct access to your class's state and so now it becomes part of the exported API. Making fields public makes your implementation part of your contract and so now you are no longer free to make any changes to that part of it. You must continue to support that public variable for as long as your class exists.
I know lots of coders use accessor methods to access some class fields which are private from other classes, but I was wondering why. And why they don't prefer protected fields witch are accessible only from classes of the same package instead of accessors? I mean if there is not a serious reason, it's just code waste.
When you only define methods to access a field, you are restricted by the methods. You cannot do something that there is not a method for.
Consider this class:
public class Account {
private int balance = 0;
public int getBalance() {
return balance;
}
public void insert(int amount) {
if(amount > 0) {
balance += amount;
}
}
public void withdraw(int amount) {
if(amount > 0 && amount =< balance) {
balance -= amount;
}
}
}
You can change the balance of the account by inserting and withdrawing, and you can check what it is. But if you had access to the balance directly, you could do something that is not supposed to be possible like:
Account acc = new Account();
acc.balance = -10;
Furthermore, protected is actually closer to public than to private. If you have a private field, it will be private forever. If your field is protected, anyone can always extend your class and access the field. If it is intended to be private and you set it to protected, it might lose its purpose when someone extends it (and the fact that he extended no longer makes sense, because his new class does not behave in the spirit of the superclass).
A mutuator method like a getter or a setter is not the same thing as a protected variable.
You have no control on when a protected variable is read or written if who is accessing it has the right to access it but a mutuator works as a bridge which is able to intercept modifications or access to an underlying member attribute and also provide different behavior from just returning/setting the value. So they don't fulfill exactly the same purpose.
In addition with mutuators you are able to provide a read-only or write-only access to a private member variable, but you can't do it with a protected field.
Using accessors/mutators methods is a common best practice in Java programming as in other languages.
Wikipedia suggests:
The mutator method is most often used in object-oriented programming, in keeping with the principle of encapsulation. According to this principle, member variables of a class are made private to hide and protect them from other code, and can only be modified by a public member function (the mutator method), which takes the desired new value as a parameter, optionally validates it, and modifies the private member variable.
So you use accessors to hide the logic (if present) applied before setting or getting the private variable value.
protected modifier instead should be used to mark variables (or methods) that are not inteded to be publicly accessible, but that should be inherited and visible by sub classes. The sub class can use this variable in its methods and/or it can expose it publicly via accessors if necessary.
I have discovered the following in some legacy code:
public class MyClass
{
private boolean myBool;
public boolean getMyBool()
{
return myBool;
}
public void otherMethod()
{
// some other calculations
boolean something = this.getMyBool();
// some other calculations
}
}
Am I missing something here? Is there an advantage to using getMyBool() and not just calling myBool directly?
Because as I see it, if the behaviour of getMyBool() changes, then this class will betray itself when calling this method.
Other classes may inherit this one, and override getMyBool() with another implementation
lazy initialization
use a static attribute
use some complex business logic
...
Another use case is when you want to instrument your code with aspects. Either for changing the getter behaviour, or for logging the getters invokations...
It is not betrayal. If you use this class and use getter/setter outside class, changing of functionality is not betrayal either.
Imagine class Person. This class have age and you want to set value lesser than zero to zero. You just change setter and/or getter to appropriate behaviour.
You really do not want changing it from below zero to zero only "sometimes". This is reason, you should call setter/getter inside class.
If getMyBool is a pure getter; that is, it only ever retrieves the field, then there's little value in making a method call to it. There's no change in behavior between the getter and the field.
If it's not a pure getter, which does occur often, then the method call is acceptable. Just using the getter wouldn't encapsulate the full intent of the program.
If you want to use myBool; in same class , you can use it directly. But you couldn't use this value in other class because it's access specifier is Private. Private members we cannot use and inherit it into other class. But you can call and get the same value from getMyBool();method. It is public method. we can use it from any where.
I was wondering if it's possible to use a variable of a java class in another java class.Suppose variable Time is defined and calculated in Class A, how can I use it in Class B?
Other answers have suggested increasing a variable's visibility. Don't do this. It breaks encapsulation: the fact that your class uses a field to store a particular piece of information is an implementation detail; you should expose relevant information via the class's API (its methods) instead. You should make fields private in almost all cases.
Likewise, some other answers have suggested possibly making the variable static. Don't do this arbitrarily. You need to understand what static really means: it's saying that this piece of information is related to the type rather than to any one particular instance of the type. Occasionally that's appropriate, but it's generally a road towards less testable code - and in many cases it's clearly wrong. For example, a Person class may well have a name variable, but that certainly shouldn't be static - it's clearly a piece of information about a single person.
You should think carefully before exposing information anyway - consider whether there's a wider operation which the class in question could expose, instead of just giving away its data piecemeal - but when you do want to expose a field's value, use a property. For example:
public class Person {
private final String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
By exposing it via a method, you can later change the implementation details without breaking existing clients.
Then from another class, you'd just call the getName() method:
// However you end up getting a reference to an instance of Person
Person person = ...;
String name = person.getName();
If you do have a static field, you can expose the value in the same way, but with a static method, which you'd call using the class name.
Be careful about returning values which are mutable, e.g. java.util.Date. This is another reason for using a getter method instead of allowing direct access to the field - you can make the method return a defensive copy where you need to.
If it is declared as public, you may use ClassA.yourVariable. On the other hand, for private access modifier, include the getter to your ClassA. On the ClassB, call ClassA.getYourVariable().
Also read about access specifiers in Java it might help.
If the variable is static, you can refer to it as A.Time from any code that has access to the variable. There's only one Time value for all of class A. If it is an instance variable, and you have an instance a of class A, you can refer to the variable as a.Time. There's a separate value for each instance of class A.
This is subject to Java's access rules:
if the field is public, any code can access it (this makes public variables kind of dangerous unless they are also declared final)
if the field is protected, only code in the same package or in a subclass of A can access it
if the field has default access, only code in the same package as class A can access it
if the field is private, only code in class A (including inner classes of A) can access it.
Alternatively, you can provide an accessor method in class A:
public class A {
. . .
public class getTime() {
return this.Time; // the "this." is optional
}
}
If you declare your Variable as public or static you will be able to access it from another class.
WHICH IS A VERY VERY BAD IDEA :)
In my current project I have a class which stores its Instance in a variable. This Instance should be accesible by all other classes in the project, but it may only be altered by its own class.
How can I achieve this?
Write a public getter but no public setter. And the field itself private
In short that is called immutable object, state of Object cannot change after it is constructed.
String is a common example of immutable Class.
Make a class immutable by following-
ensure the class cannot be overridden - make the class final, or use
static factories and keep constructors private.
make fields private and final
force callers to construct an object completely in a single step,
instead of using a no-argument constructor combined with subsequent
calls to setXXX methods.
do not provide any methods which can change the state of the object
in any way - not just setXXX methods, but any method which can change
state
if the class has any mutable object fields, then they must be
defensively copied when passed between the class and its caller.
Someone suggests "public getter but no public setter for the private field."
Caution: This would only work if the field is primitive type.
If it is an object with setters, the content can still be modified; thus not read-only.
It will be interesting to see Java language provide some constructs to make a return type read-only without having to do a deep-copy / clone.
i'm imaging like
ReadOnly getEmployee() {
...}
The boilerplate code for instantiating a singleton can be found in many places, see for example http://www.javacoffeebreak.com/articles/designpatterns/index.html
Be aware that many consider the singleton to be an antipattern because it's pretty hard to get rid of once your application is littered with references to the singleton.