class
Full Initialization process
This is an example of a full initialization process in a class. To initialize a class and its fields we have performed the following steps:
- We have created a class,
A, that has aprivate int xfield and aprotected int y. It also has aprivate static int ifield that is initialized with astaticmethodprint(String), that returns an int value. - We have also created another class,
FullInitialthat extendsA. It has a private int var that is initialized usingprint(String s)method ofA. - We create a new instance of
FullInitial. - First all
staticfields ofAare initialized, thenstaticfields ofFullInitialare initialized. Then the constructor ofAis called, and after that the constructor ofFullInitialis called,
as described in the code snippet below.
package com.javacodegeeks.snippets.core;
class A {
private int x = 9;
protected int y;
A() {
System.out.println("x = " + x + ", y = " + y);
y = 39;
}
private static int i = print("static A.i initialized");
static int print(String str) {
System.out.println(str);
return 47;
}
}
public class FullInitial extends A {
private int var = print("FullInitial.k initialized");
public FullInitial() {
System.out.println("var = " + var);
System.out.println("y = " + y);
}
private static int j = print("static FullInitial.j initialized");
public static void main(String[] args) {
System.out.println("FullInitial constructor");
FullInitial b = new FullInitial();
}
}
Output:
static Insect.i initialized
static Beetle.j initialized
FullInitial constructor
x = 9, y = 0
FullInitial.k initialized
var = 47
y = 39
This was an example of a full initialization process in a class in Java.
