Quote:
Originally Posted by alykins
for your properties (I think called 'fields' in Java) you generally just do a return of the variable...
Code:
public int getNum()
{
return i;
}
you usually have/use variables in methods because you are not always sure what the variable will be
Code:
private int computeNewNum(int varibleNumber)
{
i = (variableNumber * i)
return i;
}
// input 2
// output 20
// input 5
// output 100
if field "i" is 10 and you pass 2, it will become 20; then pass a 5- 100 and so on. That is the reason you use variables. each return would be different depending what you passed it- also i is being set. You could also use i as a static variable and do something like
Code:
private int computeNewNum(int variableNumber)
{
return (i * variableNumber);
}
// input 2
// output 20
// input 5
// output 50
see? the second one doesn't assign i.
|
That is ok - all above is true and I know what variables are and how they work. My question is - what is return statement for (apart from quiting method). Let's rewrite my example to make this method protected/private and do not initialize i.
Code:
public class Main {
int i;
protected void num(int i, int a) {
this.i = i * a;
}
public static void main (String [] args) {
Main n = new Main();
n.num(10,5);
System.out.println(n.i);
}
}
It works and shows that whatever we do to "i" value it is not necessary to return it.
Quote:
making a field private means that only that object can access it and change it via method.
Code:
public class Demo
{
private int i = 10;
public Demo(){...}
public void seti(int variableNumber)
{
i = variableNumber;
}
public int geti()
{
return i;
}
}
you can't access i in any other class. You can call the Demo.seti() and 'change' i, but you are not accessing it directly. You can throw in validation @ this point.
Code:
public void seti(int variableNumber)
{
if(variableNumber >= 0 && variableNumber <= 100)
i = variableNumber;
else
throw new exception();
}
note* syntax's might be off-
|
So once again - the only reason for writing the whole method (which job is just to return value) is to make fields and method be private/protected in other classes than the class in which we instantiate object?