Java static keyword example
- Details
- Written by Nam Ha Minh
- Last Updated on 20 August 2019   |   Print Email
This article helps you understand how to use static keyword in Java with code example.
In Java, the static keyword can be applied for inner classes, methods and variables.
- Static methods and variables are shared among all instances of a class. They can be invoked and accessed without creating new instances of the class. The following example shows a class contains a static variable, a static method and a regular method:
public class Car { static String color; static void beep() { //beep beep! } void brake() { // stop } }
The static variable color and static method beep() can be accessed like this:
Car.color = "Red"; Car.beep();
whereas the regular method brake() must be called on an instance of Car class:
Car myCar = new Car(); myCar.brake();
- A regular class cannot be static, only inner class can be static. The following example shows an example of a static inner class:
public class Car { static class Engine { } }
The inner class Engine can be instantiated without creating an instance of the enclosing class Car, for example:
Car.Engine carEngine = new Car.Engine();
See all keywords in Java.
Related Topics:
Other Recommended Tutorials:
- 9 Rules about Constructors in Java
- 12 Rules and Examples About Inheritance in Java
- 12 Rules of Overriding in Java You Should Know
- 10 Java Core Best Practices Every Java Programmer Should Know
- Understand Interfaces in Java
- Understand how variables are passed in Java
- Understand encapsulation in Java
Comments