Posts

Showing posts with the label static

Type Inference in Java

As part of Generics , Java language supports type safe programming. It allows a type or method to operate on objects of various types while providing compile-time type safety. The most common use case is while using Java Collection framework. For example if you define a list of string and trying to add integer value to the list, compiler throws error. List list = new ArrayList(); //Compilation Error : he method add(int, String) in the type List is not applicable for the arguments (int) list.add(10); As a developer you may always notice redundancy in defining parameter type information in both the side of declaration. As off Java 1.6, language doesn’t provide any feature to overcome it. Using Static Factory : One possible way to overcome this problem by using static factory methods. If you frequently use typed list or map in application then you can define generic static factory methods which returns you required typed map or list. public static HashMap getMapInstance(){ ...

Lazy initializing your code

Many time we have static fields in our Java classes. These fields are get initialized with loading of your classes and all other static fields. But many time its not the urgent to initialize few of the fields while loading the class itself. Here the concept of lazy initialization comes in picture. Consider the code below public class LazyInitilaizationTest { public static String[] field = getStringContent(); static { System.out.println( "Loading Class" ); } public static String[] getStringContent(){ System.out.println( "Initializing field" ); return new String[]{}; } public static void main(String[] args) { System.out.println( "Accessing Field" ); System.out.println(field); } } Here the class has private & static field which gets initialized by invoking getStringContent () method. Running above class prints following output Initializing field Loading Class Acce...

Non-extendable Class

First thing comes in mind when somebody say Non-extendable class , that is final class. Marking a class as “final” , no one can extends the particular class. But there is another tricky way to restricting any other class from extending your class. Thinking how ….? Simple, marking all available constructors of  a class as private. As per constructor chaining principle in class hierarchy , every child class constructor should delegate call to super class explicitly or implicitly. In implicit case, call get delegate to class’s default constructor. If all available constructors of the class are private then no other class can not extend it. 1: public class MyClass { 2: 3: private MyClass(){ 4: System.out.println(" Inside Singleton Constructor "); 5: } 6: 7: } 8: 9: class MyChildClass extends MyClass{ // compilation error 10: 11: }