Skip to main content

Java Programming: Static Block vs Instance Initializer Block


 What will be the output of the following code?


class A {
  
  static {
    System.out.println("Inside static block A");
  }
  {
    System.out.println("Inside init block A");
  }
}

class B extends A {
  
  static {
    System.out.println("Inside static block B");
  }
  {
    System.out.println("Inside init block B");
  }
}

public class Test {
  public static void main(String[] args) {
    A b = new B();
  }
}

Answer:

Inside static block A
Inside static block B
Inside init block A
Inside init block B


In Java, static blocks are executed first, followed by instance initializers.

In inheritance, the parent class is initialized before the child class.

Remember, there are restrictions on using the super keyword inside the child class constructor.

Comments

Popular posts from this blog

Intersection of exception in class or interface hierarchy

Question? Q1. Will below program compile? public class ExceptionTestForInterface implements Type3 {   public void f()   {     System. out .println( "Hello World" );   }      public static void main(String[] args )   {     Type3 type = new ExceptionTestForInterface();     type .f();   } } interface Type1 {   void f() throws CloneNotSupportedException; } interface Type2 {      void f() throws InterruptedException;    } interface Type3 extends Type1, Type2{    } Ans => Yes, It will compile and successfully print the "Hello World" Remember The set of checked exceptions that a method can throw is the intersection of the sets of checked exceptions that it is declared to throw in all applicable types.

Method overloading parameter as float, double and wrapper.

Question?  What is the output of below code ?   Other question  will it be compile ? will there be an error at runtime for ambiguity?     public   class  RedHatQuestion {    public   void  printData( float   f )   {     System. out .println( "inside float" );   }       public   void  printData( double   d )   {     System. out .println( "inside double " );   }       public   void  printData(Double  d )   {     System. out .println( "Inside object double" );   }       public   static   void  main(String[]  args ) {     RedHatQuestion  question  =  new  RedHatQuestion();      question .printData(3.1415)...