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 a private int x field and a protected int y. It also has a private static int i field that is initialized with a static method print(String), that returns an int value.
  • We have also created another class, FullInitial that extends A. It has a private int var that is initialized using print(String s) method of A
  • We create a new instance of FullInitial.
  • First all static fields of A are initialized, then static fields of FullInitial are initialized. Then the constructor of A is called, and after that the constructor of FullInitial is 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.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button