Static and non-static fields and methods in Java
Can a method be declared abstract and static at the same time
Not. In this case, the compiler will issue an error: "Illegal combination of modifiers: ‘abstract’ and ‘static’”. The abstract modifier says that the method will be implemented in another class, while static, on the contrary, indicates that this method will be available by the class name.
What is the difference between an instance member of a class and a static member of a class
The static modifier indicates that this method or field belongs to the class itself and can be accessed even without creating an instance of the class. Fields marked static are initialized when the class is initialized. Methods declared static have a number of restrictions:
- They can only call other static methods.
- They should only access static variables.
- They cannot refer to members of type this or super.
Unlike static fields, the fields of a class instance belong to a specific object and can have different values for each. An instance method can only be called after the class object has been previously created.
Example:
public class MainClass {
public static void main(String args[]) {
System.out.println(TestClass.v);
new TestClass().a();
System.out.println(TestClass.v);
}
}
public class TestClass {
public static String v = "Initial val";
{
System.out.println("!!! Non-static initializer");
v = "Val from non-static";
}
static {
System.out.println("!!! Static initializer");
v = "Some val";
}
public void a() {
System.out.println("!!! a() called");
}
}
Result:
!!! Static initializer
Some val
!!! Non-static initializer
!!! a() called
Val from non-static
Where is static/non-static field initialization allowed
- Static fields can be initialized on declaration, in a static or non-static initialization block.
- Non-static fields can be initialized on declaration, in a non-static initialization block, or in a constructor.
Read also:
- Static modifier, initialization blocks and exceptions in it in Java
- Overriding and overloading methods in Java
- What is the order of calling constructors and initialization blocks, given the class hierarchy
Comments
Post a Comment