- 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:
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on
Facebook and watch
his Java videos you YouTube.