I am starting to learn Java and have a nooby question. I have a set of instances in my class block with 2 methods, 1 main static, and 1 void
public class CurrencyConverter {
int rupee = 63;
int dirham = 3;
int real = 3;
int chilean_peso = 595;
int mexican_peso = 18;
int _yen = 107;
int $austrailian = 2;
int dollar = 0;
int Rupee = 63;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
CurrencyConverter cc = new CurrencyConverter();
cc.printCurrencies();
}
void printCurrencies() {
System.out.println("rupee: " + rupee);
System.out.println("dirham: " + dirham);
System.out.println("real: " + real);
System.out.println("chilean_peso: " + chilean_peso);
System.out.println("mexican_peso: " + mexican_peso);
System.out.println("yen: " + _yen);
System.out.println("australian: " + $austrailian);
System.out.println("dollar: " + dollar);
System.out.println("Rupee: " + Rupee);
}
}
Now my question, why do I need to instantiate my CurrencyConverter class in order to call printCurrencies()? Can't you normally just call methods anyway? I am in the same class block?
I tried changing the access modifier of printCurrencies() to static but then my local variables aren't static
Why do I NEED to instantiate?
Non-static fields are associated with an instance. You have one copy of these fields per instance.
public class CurrencyConverter {
int rupee = 63; // non static instance field
int dirham = 3; // non static instance field
// etc.
why do I need to instantiate my CurrencyConverter class in order to call printCurrencies()?
Without an instance, you have zero copies thus nothing to print.
Can't you normally just call methods anyway?
If you make the method static and remove all references to instance fields, then yes, you could. This runs just fine, but it no longer does anything useful.
public static void main(String[] args) {
printCurrencies();
}
static void printCurrencies() {
}
I am in the same class block?
Not sure what you mean, but there is only one class and everything is in it.
int rupee = 63;
int Rupee = 63;
Don't do this unless you like confusion. You should make the different purpose of each field clear in the name.
I tried changing the access modifier of printCurrencies() to static but then my local variables aren't static. Why do I NEED to instantiate?
A copy of the non-static fields doesn't exist until you explicitly create them.