Java static and this Keywords
static and this are two keywords which every Java developer must understand.
static fields: one copy for the class
A normal (instance) field has a copy in every object. A static field has only one copy shared by all the objects.
class Student {
static int count = 0; // shared
String name; // one per object
Student(String name) {
this.name = name;
count++;
}
}
public class Main {
public static void main(String[] args) {
new Student("Riya");
new Student("Aman");
new Student("Meera");
System.out.println("Students created: " + Student.count); // use the class name
}
}
Output
Students created: 3
static methods
A static method belongs to the class. You call it with the class name, and no object is needed. That is why main is static.
class MathUtil {
static int square(int n) {
return n * n;
}
static final double TAX_RATE = 0.18; // a constant
}
public class Util {
public static void main(String[] args) {
System.out.println(MathUtil.square(7));
System.out.println(MathUtil.TAX_RATE);
System.out.println(Math.max(3, 9)); // Math has static methods
}
}
Output
49
0.18
9
A static method can not use instance fields or this, because it does not belong to any object:
class Person {
String name = "Riya";
static void show() {
System.out.println(name);
}
}
public class Bad {
public static void main(String[] args) {
Person.show();
}
}
Output
Bad.java:5: error: non-static variable name cannot be referenced from a static context
System.out.println(name);
^
1 error
error: compilation failed
static block
class Config {
static final String VERSION;
static { // runs once, when the class is loaded
System.out.println("Loading config...");
VERSION = "1.0";
}
}
public class Block {
public static void main(String[] args) {
System.out.println("Start");
System.out.println(Config.VERSION);
}
}
Output
Start
Loading config…
1.0
The this keyword
this is a reference to the current object. Its main uses:
- To separate a field from a parameter with the same name:
this.name = name; - To call another constructor:
this(...) - To pass the current object to another method.
class Account {
private double balance;
Account(double balance) {
this.balance = balance;
}
Account deposit(double amount) {
this.balance += amount;
return this; // allows method chaining
}
double getBalance() {
return balance;
}
}
public class This {
public static void main(String[] args) {
Account a = new Account(100);
a.deposit(50).deposit(25); // chaining
System.out.println(a.getBalance());
}
}
Output
175.0
Note:
Do not use static for everything. It makes the code hard to test and to change. Use it for constants and for helper methods which do not need any object data. Next: Java Encapsulation.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |