Java Static Constructor : is it possible to create static constructor?
- No. We can not create constructor with static.
- If we try to create a static constructor compile time error will come: Illegal modifier for the constructor
2.What is the real use of constructor in java?
- Constructors will be used to assign instance variables with default values.
- Whenever object is created constructor will be called so the default values for the instance variables will be assigned in this constructor.
- Top 15 Java Interview Questions on Constructors
- public class ConstructorDemo {
- int a,b;
- ConstructorDemo (int x, int y){
- a=x;
- b=y;
- }
- public static void main(String[] args) {
- ConstructorDemo ob= new ConstructorDemo ();
- }
- }
3. What is the use of static in java?
- Static keyword is mainly used for memory management.
- Static variables get memory when class loading itself.
- Static variables can be used to point common property all objects.
- Static means class level.
- Constructor will be use to assign initial values for instance variables
- static and constructor are different and opposite from each other.
- To assign initial values for instance variable we use constructor.
- To assign static variables we use Static Blocks
- We can use static blocks to initialize static variables in java.
5.what is static block in java?
- Class loading time itself these variables gets memory
- Static methods are the methods with static keyword are class level. without creating the object of the class we can call these static methods.
- public static void show(){
- }
- Static block also known as static initializer
- Static blocks are the blocks with static keyword.
- Static blocks wont have any name in its prototype.
- Static blocks are class level.
- Static block will be executed only once.
- No return statements.
- No arguments.
- No this or super keywords supported.
- static{
- }
- package com.staticInitializer;
- class StaticBlockDemo
- {
- static{
- System.out.println("First static block executed");
- }
- static{
- System.out.println("Second static block executed");
- }
- static{
- System.out.println("Third static block executed");
- }
- }
- First static block executed
- Second static block executed
- Third static block executed