I created a class named bank.java that has a bunch of different things it does i
ID: 3689499 • Letter: I
Question
I created a class named bank.java that has a bunch of different things it does in the class. Below is the class where my main method is. I am going to used checking and savings variable names in an event handler I will set up later in the program. Can someone please explain to me why I need to declare "Static bank Checkings;" below like this? why I need to USE STATIC. I am little confused and want to make sure I understand before i proceed.
public class EXAMPLE extends JFrame {
JButton button1;
JButton button2;
JTextField xfield;
static bank checkings;
static bank savings;
public EXAMPLE() {
super("The title");
setLayout(new FlowLayout());
button1 = new JButton("num1");
add(button1);
button2 = new JButton("num2");
add(button2);
xfield = new JTextField(15);
add(xfield);
Explanation / Answer
Answer:
Java static variable:
If you declare any variable as static, it is known static variable.
Java static method
If you apply static keyword with any method, it is known as static method.
If you want to use variables inside the static method then these variables should be a type of static only. Becuase static methods will always use static variables only. Since you are trying to use these variables in main method you should mention them like static variables because main method in java is static method.
public static void main(String arg[]){
}
You can not declare varibale as static inside a method.
Inside method all variables are local variables that has no existance outside this method thats why they cann't be static.
The Root cause: Static Variables are allocated memory at class loading time because they are part of the class and not its object.
Now, if static variable is inside a method, then that variable comes under the method's scope and JVM will be unable to allocate memory to it.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.