1
JMenuItem print = new JMenuItem("Print");
print.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));

I'm new to java. I have learned that if we want to access the contents of class then we have to first create an object of that class. Then we can use that object to access the class's contents. But here KeyEvent and ActionEvent are classes and they can access their fields VK_P and CTRL_MASK without the help of any object. How is this possible?

flaxel
  • 4,173
  • 4
  • 17
  • 30
  • These two fields are `static` so you don't need to create an object of the class to access them. You can refer the Java docs for the same https://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html – nehacharya Feb 27 '21 at 11:46
  • Does this answer your question? [Static Classes In Java](https://stackoverflow.com/questions/7486012/static-classes-in-java) – flaxel Feb 27 '21 at 11:47
  • @flaxel That doesn't really address the problem of this question – Mark Rotteveel Feb 28 '21 at 09:42
  • Does this answer your question? [What does the 'static' keyword do in a class?](https://stackoverflow.com/questions/413898/what-does-the-static-keyword-do-in-a-class) – Progman Feb 28 '21 at 14:55

3 Answers3

3

Static variables, or variables initialized with a static keyword, are able to be accessed without instantiation of a class object since they are not tied to a particular instance of the class but the actual class itself.

berlin
  • 506
  • 4
  • 14
1

You can access a class's variable without via an instance of that class if that variable is static.

hutra
  • 11
  • 1
0

Static variables, or variables declared with a static keyword, are class level data members NOT instance/object level. This means - the same static variable is common to all instances of the class and they all can access it (!!). public class Perrson{ public static int personCounter;

mean: you can access personCounter as Person.personCounter++ for instance..

However, when you have Person instances p1, p2,... p1.personCounter++ p2.personCounter++ access the same variable !

It is good for example for object counter when Person constructor advances the counter.

by yl

ylev
  • 2,313
  • 1
  • 23
  • 16