MAP

Showing posts with label CORE JAVA PROGRAMS. Show all posts
Showing posts with label CORE JAVA PROGRAMS. Show all posts

Initialization block in JAVA | Java - Initializer block | java tutorial | Static initialization block in java | Non static initialization block in java | Initialization block in JAVA with example

An initialization block is a block of code between braces that is executed before the object of the class is created. As the execution of the initialization block is dependent on the creation of the object we can easily make a guess that it has two types of object.


1. Non static initialization block.
2. Static initialization block.
 

1. Non static initialization block.

It is dependent on the object and the initialization block is executed for each object of the class that is created. It can initialize instance member variables of the class. Here is a simple example.


2. Static initialization block.

It is defined using the keyword static and is executed once when the class is loaded and has a restriction that it can only initialize static data members of the class.

The only difference between both the samples above is with the two static keywords added and you can definitely see difference in the output. One outputs different values for two objects created and other one the same values.

You can have multiple initialization blocks in a class in which case they execute in the sequence in which they appear in the class.

Note that any initialization block present in the class is executed before the constructor.

So now the question comes why we need constructors if we have initialization blocks. The answer is we don't need the default constructor but initialization block cannot be parameterized and so you cannot have objects taking values from out side and so initialization block is not a substitute for constructor.
 
  1. A block defined using the keyword static.
  2. Executed once when the class is loaded.
  3. Can initialize only static data members of the class.
 
 
 
java code
 
public class MainClass {
  static int[] values = new int[10];

  static {
    System.out.println("Running initialization block.");
    for (int i = 0; i < values.length; i++) {
      values[i(int) (100.0 * Math.random());
    }
  }

  void listValues() {
    for (int value : values) {
      System.out.println(value);
    }
  }

  public static void main(String[] args) {
    MainClass example = new MainClass();
    System.out.println("\nFirst object:");
    example.listValues();

    example = new MainClass();
    System.out.println("\nSecond object:");
    example.listValues();
  }
}
 
 
OUTPUT
 
Running initialization block.

First object:
58
22
49
75
1
35
76
19
27
63

Second object:
58
22
49
75
1
35
76
19
27
63
 
--------------------------------------------------------
 
I discovered yesterday a feature of the Java language that I didn’t know of: initialization blocks. This is something that we rarely see in code, hence you may not be aware of their existence too…
You probably already know of static initialization blocks such as:

public class Foo {
 
    public static final int MY_INT;
 
    static {
        MY_INT = 1;
    }
 
}
 
In this example, the static block is called when the Foo class is loaded by a classloader. It can perform anything you want of course, but its main purpose is to eventually initialize / configure static class fields.
What I didn’t know is that you can have such blocks at the class instance level as well:

public class Bar {
 
    private int myInt;
 
    {
        myInt = 1;
    }
 
}
 
Here this block is called before the Bar class constructors. It can do anything including touching instance fields.
I must confess that I can hardly see a use-case for this lesser-known feature of the Java language since one is more likely to use a constructor for such tasks.
It may be sometimes nicer to read with anonymous classes though:

MyListener listener = new MyListener() {
    {
        bind("this").with("that");
        // etc
    }
};
 
What do you think? Have you ever seen a great application of those blocks? I’m really curious! :-) 

 

 

 
 

Abstract methods and classes


While going through the java language programming you have learned so many times the word abstract. In java programming language the word abstract is used with methods and classes. 
Abstract Method
An abstract method one that have the empty implementation. All the methods in any interface are abstract by default. Abstract method provides the standardization for the " name and signature" of any method. One can extend and implement to these methods in their own classes according to the requirements.   
  e.g.
public abstract abs_value();
Abstract Class
In java programming language, abstract classes are those that works only as the parent class or the base class. Subclasses are derived to implement the methods inherited from the abstract class (base class). Abstract classes are not instantiated directly. First extend the base class and then instantiate (create objects). Abstract classes are generic in nature and implement to those methods that are used commonly by the subclasses with common implementation. Abstract classes .
e.g.
abstract class A{
   public abstract abs_value();
   
   void show(){
     System.out.println("This is an abstract class");
   }
 }

Java Abstract Class Example

<html>
    <head>
        <title>Using Abstract Classes</title>
    </head>
    <body>
        <h1>Using Abstract Classes</h1>
        <%!
            javax.servlet.jsp.JspWriter pw;
            abstract class Rectangle
            {
               int length, breadth, area;
 abstract int getArea() throws java.io.IOException;
 public void setArea(int length, int breadth) throws java.io.IOException 
                {
                       this.length = length;
                       this.breadth = breadth;
                       pw.println("Calculating the area of a rectangle...........<br>");
                       pw.println("The area of rectangle is  ");
                       pw.println(getArea());
                }
            }
            class Rectangle1 extends Rectangle
            {
                int getArea() throws java.io.IOException 
                {
                    area = length*breadth;
                    return(area);
                }
            }
        %>     
        <%
            pw = out;     
            Rectangle1 rect = new Rectangle1();
            rect.setArea(2,3);
        %>
    </body>
</html>

Twitter Delicious Facebook Digg Stumbleupon Favorites More