Saturday, 18 June 2016

static and instance init. block

Init. block is located in the class body, could be anywhere.

Static initialize block: used for init. static variables; it will be invoked as class loaded. One class could have several static init. blocks. they will be invoked by the sequence in the body.

static {
//whatever code here
}


Instance initialize block: used for init. instance variables, and shared by the overloaded constructors. On compiling time, the instance init. block will be copied into each overloaded constructors. So static init. block is always invoked earlier than instance init. block.

{
//whatever code here
}



/**
 *
 * @author YNZ
 */
public class InitBlocks {

    static float sp;
    final static Integer[][] matrix = new Integer[2][3];
    Float[][] instMatrix = new Float[4][6];

    //static init block is a place to init satic field, 
    //as it cannot be done in one line.
    static {
        Random r = new Random();
        for (Integer[] matrix1 : matrix) {
            for (int j = 0; j < matrix1.length; j++) {
                matrix1[j] = r.nextInt(100);
            }
        }
    }

    {
        Random r = new Random();
        for (Float[] row : instMatrix) {
            for (int i = 0; i < row.length; i++) {
                row[i] = r.nextFloat();
            }
        }
    }

    InitBlocks() {
        //if static field can be modified in the instance. 
        sp = 20;
    }
    
    static  void printMatrix(T[][] mat){
        for(T[] row: mat){
            System.out.println(Arrays.toString(row));
        }
    }

    public static void main(String[] args) {
        printMatrix(InitBlocks.matrix);
        InitBlocks ib = new InitBlocks();
        printMatrix(ib.instMatrix);
    }
}


Thursday, 16 June 2016

What consequence as declaring a private non-arg constructor?

In inheritance context:

private constructor is invisible to the sub-classes. This might cause a compiling error, "no suitable constructor found" as defining a subclass, especially as a non-arg user-defined constructor has been explicitly defined.

Here is a case: Line //1 generates a compiling error.

Reasons:

1) as having no any user-defined constructor, Java will automatically add a default constructor.
2) a default constructor is non-arg constructor, in which super() will be added in the first line; and instance variable will be init. immediately following.

/**
 *
 * @author YNZ
 */
class A {
    int a;
    int b;

    //invisible to subclass
    private A() {

    }

    public A(int a, int b) {
        this.a = a;
        this.b = b;
    }

    protected A(float a, int b) {
        this.a = (int) a;
        this.b = b;
    }

}

class B extends A {  //1

}






how about removing it?
class A {
    int a;
    int b;

    public A(int a, int b) {
        this.a = a;
        this.b = b;
    }

    protected A(float a, int b) {
        this.a = (int) a;
        this.b = b;
    }

}

class B extends A {  //1

}

this will still cause the same compiling error. since there is only argument constructors have been defined, the sub-class will think, non-argument constructor has no been defined.

How about removing all constructors from A? it should be correct. As compiling time, a default non-arg constructor will be added by Java with in the A; and a default non-argument constructor will be added by Java with in the B, in which a super() being invoked from the A.


So the following should be correct.
class A {
    int a;
    int b;
}

class B extends A {  //1

}

Can switch accept Object type?


I think, no.

This question comes from an open discussion.

Rules:
switch(x) may accept primitive and reference variable.

(1) primitives: byte, char, short, and int
(2) reference type: their boxing, i.e Byte, Character, Short, and Integer; as well as String and Enum

The above is all types that switch is able to handle.

The following code will give a compiling error, although reference types mentioned above are Object too. However, Object is not a String,  Byte or a Integer.

public class AcceptObject {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Object i = new Integer(9);
        
        switch(i){
            default:System.out.println("dd");
        }
        
    }
    
}


Friday, 3 June 2016

does casting change variable type?

Principle: narrowing: when assigning a large data type(base type) to a type smaller one(child type); for instance, assigning a super-class type  to its sub-class type, or assigning a double primitive to a float; then it needs an explicit type casting.

Assume:
Double d = 12.0
Number n = (Number)d;

Question:
Is n become an instance type of Number?

public class InstanceTypeAfterCasting {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Double d = 12.0d;

        System.out.println("n type is Number " + Boolean.toString((Number)d instanceof Number));//1
        System.out.println("n type is Double " + Boolean.toString((Number)d instanceof Double));//2
        
        Number n = d;//3
        Double m = (Double)n; //4
        Double o = n; //5
        
        
    }
}

//1 //2

The code above shows that d is still Number and Double after casting. So what casting means? it won't change the dynamic object type. it doesn't mean cutting off part from d object and leaving it like a Number object.  Physically, d object haven't been altered after casting, but  it tells compiler a specific scope, in which specific instance members are accessed. This is due to Java inheritance mechanism, where instance methods can be overridden and instance variable can be hidden in sub-classes.

//3
Number is the base class of Double; so it may assign  a double to a Number. it reflects an IS-A relationship, i.e. d is a n.

//4
You cannot assign  n to m directly, for Number is not a Double. then it needs a casting before assigning. In this case, Number's run-time object is indeed a double. So it is a valid casting.

//5
it causes a compiling error, for Number is not a Double, although Double is a Number.

Conclusion: casting should be a compiling notification.


Thursday, 2 June 2016

Exception

Exceptions are divided into three categories: checked exception, un-checked exception, and errors
The checked is a direct sub-class of exception class.
The un-checked is a direct sub-class of runtime exception class.
The error is  a direct sub-class of error class

In my understanding, checked for the fault due to user; un-checked due to the fault of developer bad coding; error for the Java VM's faults.

The checked is foreseen by the author, and must be handled in try-catch block, or throws to the caller.
The un-checked may not be caught, even not be declared in the method signature.
The error should be left to the JVM to handle.

All exceptions are derived from throwable class, which is direct sub-class of an object class.
Custom Exception -  Exceptions - Throwable - Object
IllegalStateException - RuntimeException -  Exceptions - Throwable  - Object
Error   -  Throwable - Object

Note: You may catch un-checked or error, or re-throw them. This won't be a fault. Normally, error is handled by JVM;  (How runtime Exception is handled? I need figure out)

Checked exception is foreseen by the writer, or say it is defined by a developer who predicts on such a condition this exception should pop out. For instance, file not found exception. As file is not found in runtime, it needs to change current process and turning to another process, so that the program can be terminated elegantly or present the user another process. In some sense, this is the meaning why ask developer to predict and manage an exception, which need to be checked.

Un-checked exception happens on an existing code, which is not correctly used. For instance, index out of bound exception, class definition is not found, illegal state exception, illegal argument format, number format invalid and null pointer exception. In my understanding, when this kind of exception happens, it is hard to get program quit in a good manner. In a simple word, it is not a fault due to user inputs or whatever. This is the problem due to the code.

Errors happens with JVM, mostly due to the resources running out, and it cannot be recovered.  for instance stack overflow exception, or others like the running out permanent  memory or heap memory etc. It is critical, and requires the program to be terminated immediately.


How to declare a custom exception. it must be checked.

public class MyException extends Exception {

    public MyException() {
        super();
    }

    public MyException(String message) {
        super(message);
    }

}




So, checked exception requires developer to provide handler in a try {...} catch {...} finally{}.

Throwing Exception: throwable can be thrown.
if not handled then throw new MyException("msg") to the caller.

Please note: 1) any throwable sub-class can be thrown. it doesn't means only custom exception can be thrown.  2) catch exception from the bottom of the exception inheritance structure; otherwise, it will cause unreached catch block; this will be a compiling error. 3) it is not a good practice to catch RuntimeException or Exception base classes. 4) you should not empty catch, at least having a finally block;

Exception alter Program Flow
1) once an exception thrown and caught, the rest of  code will be over-skipped. So some code lines may not be implemented anyway, for instance, return clause. This should cause a compiling error, i.e. something like " un-reachable code".

try-catch
try-finally
try-catch-finally
try-with-resources: file IO or network streaming are considered as resources. They can be closed automatically.


multiple-catch: exception should not have direct inheritance relationship. Otherwise it will give a compiling error, i.e.  "Alternatives in a multi-catch statement cannot be related by sub classing". The reason is because the sub-class exception handler won't be triggered, for it has been caught and handled in its generic type. You may combine single catch and multi-catch together to solve this issue. In addition, in a multiple catch clause, it needs to use a single exception variable, but not multiple exception variables. Otherwise, it causes a compiling error.

    public void setAddress(Address address) {
        if (address != null) {
            try {
                GPSCoordinate gPSCoordinate = GoogleGeoCoder.getGPSCoordinate(address);
                setCoordinate(gPSCoordinate);
            } catch (InvalidKeyException | IOException | GoogleGeoCoderException ex) {
                Logger.getLogger(Yard.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

Please note: whatever finally block will be implemented, if the program is not terminated before it; for instance, system exist.

Wednesday, 1 June 2016

Reference variable type, actual Object type and Polymorphism

What is Polymorphism in Java?  literally, polymorphism  means many forms. Different living being may have the same behaviors, but react differently according to their own. A lion and a bird are both living beings, but they eat in different manners.

Just like in a real life, Java provides a mechanism to model this phenomena, and implemented by an way of method overriding in an inheritance hierarchy. this also incur the run-time method selection of object type refer to the reference variable type.

The tricky part maybe here, a reference variable could be declared as its base class or implemented interfaces,  however its instantiated instances could have different forms modeled by its sub-classes. I think, this is also a kind of so called polymorphism.  Declaring in a generic form, a super type, but it could be implemented by different concrete sub-types.

However, a critical concept of the polymorphism is about the method overriding. Super-class's instance methods can be inherited by the child classes, but where they can be overridden. So, for a super-class form, it not only could have different forms of run-time objects, but also their same methods can have different forms.

As overriding happens, invoking a method via a reference variable types, it needs to watch out which instance method has been pointed to. This depends on reference variable's run-time object.

Please note: an overridden method, just like its literal meaning, in the sub-class scope its super-class one has been destroyed. On this case, even for the super-class, it have to invoke its sub-class overridden one.













keyword 'super' and 'this'


Both refer to instance(object) members(variables and methods). So you cannot use them in a static context.

'this' refers to current instance itself, including inherited parts. (1) it is used to distinguish instance variable from the local variable or method parameters. (2) it is used to refer to another constructor of the same class. (3) this refers to instance members inherited from the super classes, if they are not hidden or overridden.

Please note: on (2), you must use 'this' to refer to other overloaded constructors in a constructor; you cannot seating within a constructor then invoking another overloaded constructor by its name.

'super' refers to current instance's super-class instance; you can only access one more layer higher. (1) in the first line of the constructor to invoke its super-class constructor. (2) when super class's instance members are hidden in child class; then you may use super keyword to refer them in the sub-class.

please note: calling of super() and this() must be in the first line of constructor.

Call of super class
If there is no super constructor present in the sub-class constructor, jvm will automatically insert a non-argument, super(), in the first line of constructor. so you need to watch out here, if you explicitly declare an constructor with argument in the super class alone; then you will get a compiling error,

Can Jackson Deserialize Java Time ZonedDateTime

Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...