Java Access Modifiers – public, protected, private and default笔记

1 . Java static variables: We can use static keyword with a class level variable. A static variable is a class variable and doesn’t belong to Object/instance of the class. Since static variables are shared across all the instances of Object, they are not thread safe. Usually static variables are used with final keyword for common resources or constants that can be used by all the objects. If the static variable is not private, we can access it with ClassName.variableName

//static variable example
private static int count;
public static String str;
public static final String DB_USER = "myuser";

2 . Java static methods: Same as static variables, static methods belong to class and not to class instances. A static method can access only static variables of class and invoke only static methods of the class. Usually static methods are utility methods that we want to expose to be used by other classes without the need of creating an instance; for example Collections class. Java Wrapper classes and utility classes contains a lot of static methods. The main() method that is the entry point of a java program itself is a static method.

//static method example
public static void setCount(int count) {
    if(count > 0)
    StaticExample.count = count;
}
 
//static util method
public static int addInts(int i, int...js){
    int sum=i;
    for(int x : js) sum+=x;
    return sum;
}

From Java 8 onwards, we can have static methods in interfaces too, for more details please readJava interface static methods.

3 .Java static Block: Java static block is the group of statements that gets executed when the class is loaded into memory by Java ClassLoader. It is used to initialize static variables of the class. Mostly it’s used to create static resources when class is loaded. We can’t access non-static variables in static block. We can have multiple static blocks in a class, although it doesn’t make much sense. Static block code is executed only once when class is loaded into memory.

static{
    //can be used to initialize resources when class is loaded
    System.out.println("StaticExample static block");
    //can access only static variables and methods
    str="Test";
    setCount(2);
}

4 . Java Static Class: We can use static keyword with nested classes. static keyword can’t be used with top-level classes. Static nested class is same as any other top-level class and is nested for only packaging convenience.Read: Java Nested Classes

摘自:http://www.journaldev.com/7153/java-101-tutorials-learn-java

你可能感兴趣的:(Java Access Modifiers – public, protected, private and default笔记)