Java (access question)

  • Java
  • Thread starter Bleys
  • Start date
  • #1
74
0
Hello there; I have a very short question about client class access:

Suppose in a supplier class an instance variable is declared private (and is used in the constructor), and a void method in the same class (declared public) changes this variable. In the client class, is calling this method still going to change the variable (assuming an object of that class is instantiated of course). I know if the method is called within its own class then the variable will be changed, no problem. I was wondering whether the fact it's being called outside of its class makes a difference.
Something like:

public class Auto(){
private int gas;

public Auto(){
gas = 0
}

public void addGas(int g){
gas = gas + g;
}
}

and if addGas is called somewhere outside of the class, will the gas variable still be accessed and changed?
 

Answers and Replies

  • #2
35,396
7,273
Hello there; I have a very short question about client class access:

Suppose in a supplier class an instance variable is declared private (and is used in the constructor), and a void method in the same class (declared public) changes this variable. In the client class, is calling this method still going to change the variable (assuming an object of that class is instantiated of course). I know if the method is called within its own class then the variable will be changed, no problem. I was wondering whether the fact it's being called outside of its class makes a difference.
Something like:

public class Auto(){
private int gas;

public Auto(){
gas = 0
}

public void addGas(int g){
gas = gas + g;
}
}

and if addGas is called somewhere outside of the class, will the gas variable still be accessed and changed?
Yes, but it will not be accessed directly. Your public method addGas will do that.

Code:
Auto car = new Auto();
car.addGas(10);

The car instance is created with its gas property initialized to 0. The next line calls the addGas method to add 10 (gallons, liters?) of gas.
 
  • #3
74
0
thank you, Mark!
 
  • #4
35,396
7,273
You're welcome!
 

Related Threads on Java (access question)

  • Last Post
Replies
5
Views
4K
  • Last Post
Replies
3
Views
2K
  • Last Post
Replies
2
Views
2K
  • Last Post
Replies
2
Views
2K
  • Last Post
Replies
4
Views
3K
  • Last Post
Replies
1
Views
2K
  • Last Post
Replies
4
Views
1K
Replies
11
Views
2K
Replies
2
Views
1K
Replies
6
Views
737
Top