Q:

Java program to explain static block and constructor

0

Java program to explain static block and constructor

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

//Java program to explain static and constructor block.

import java.util.*;
class Sample {
    static {
        System.out.println("**This is STATIC BLOCK.");
    }

    public Sample() {
        System.out.println("##This is CONSTRUCTOR.");
    }
    public void showMessage() {
        System.out.println("Hello World.");
    }
}

public class StaticAndConstructor {

    public static void main(String s[]) {
        Sample S1 = new Sample();
        Sample S2 = new Sample();
        Sample S3 = new Sample();

        S1.showMessage();
        S2.showMessage();
        S3.showMessage();
    }
}

Output:

**This is STATIC BLOCK.
##This is CONSTRUCTOR.
##This is CONSTRUCTOR.
##This is CONSTRUCTOR.
Hello World.
Hello World.
Hello World.

Explanation:

Here "**This is STATIC BLOCK." called once because this message was written into static block, Message "##This is CONSTRUCTOR." called three time because it was written in constructor and when object created constructor called. "Hello World." called three time because it was written in method showMessage() and this method called three time.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now