Sunday, 26 June 2016

Can abstract have a static main method?

Yes. it can.

abstract class means it cannot be instantiated into objects. However, invoking a static method doesn't depends on any instance of a class. So even abstract class it is able to have static main method.


Friday, 24 June 2016

Guessing what is the output?


try - catch -finally maybe not that simple.

principle:
1) finally block will be operated regardless of return clause. Even it returns in the inner catch block, but outer finally block will still be operated no matter what.
2)
3) return will quite from current position and return control back to the main method.
4) finally block will be operated regardless if there is or not an exception caught.
5) FileNotFoundException is a checked exception.
6) IndexOutOfBoundsException is a un-checked (Runtime) exception, I explicitly catch it here.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

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

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        try {
            try {
                FileReader fr = new FileReader(new File("test.txt"));
            } catch (FileNotFoundException ex) {
                System.out.println("File not found");
                return;
            } finally {
                System.out.println("inner final");
            }
            System.out.println("try outer");
            int[] ary = new int[2];
            ary[0] = 10;
            ary[5] = 20;

        } catch (IndexOutOfBoundsException ex) {
            System.err.println("Index out of bounds");

        } finally {
            System.out.println("outer final");
        }

        System.out.println("next task");
    }

}






How about moving return also in the finally block?
this gives a compiling error, for //3 cannot be reached.

    public static void main(String[] args) {

        try {
            try {
                FileReader fr = new FileReader(new File("test.txt"));
            } catch (FileNotFoundException ex) {
                System.out.println("File not found");
                return;  //1
            } finally {
                System.out.println("inner final");
                return;  //2
            }
            System.out.println("try outer"); //3
            int[] ary = new int[2];
            ary[0] = 10;
            ary[5] = 20;

        } catch (IndexOutOfBoundsException ex) {
            System.err.println("Index out of bounds");

        } finally {
            System.out.println("outer final");
        }

        System.out.println("next task");
    }

}



Sunday, 19 June 2016

super() implicitly added in sub-class constructor


If sub-class constructor does not explicitly invoke any super-class constructor, a super() will be automatically added in the first line of sub-class constructor.

class Father {

    public Father() {
        System.out.println("in father!");
    }

    public Father(String wife) {
        System.out.println("in father wife!");
    }

}

class Kid extends Father {

    public Kid() {
        System.out.println("in kid!");
    }

    public Kid(String mother) {
        System.out.println("in kid mother!");
    }

}

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

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        Kid kid = new Kid();
        System.out.println("----");
        Kid kid1 = new Kid("mother");
    }

}


output
run:
in father!
in kid!

in father!
in kid mother!


so when sub-class doesn't explicitly invoke any super-class constructor, and mean while super class has no non-argument constructor defined, it will cause an compiling error.

Implicit and explicit casting


Implicit casting, moving from a small container to a big container.
OR:
Explicit casting, moving from a big container to small container.

byte (8)  short(16)  int(32)  long(64)  float(32)  double(64)
excluding char(16) un-singed

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

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        byte b = 127;
        short s = b;
        int i = s;
        long l = i;
        float f = l;
        double d = f;

        //byte short int long are integer types, but not char
        //char is not integer and decimal(floating)
        char c = 10000;
        c = (char) b;
        c = (char) s;
        c = (char) i;
        c = (char) l;
        c = (char) f;
        c = (char) d;

        i = c;  //int is big enough to  hold char
        l = c;  //long is big enough
        s = (short) c;  //no
        b = (byte) c;   //no
        f = c;
        d = c;
    }

}



Can new an Interface or Abstract class?


Both interface and abstract class cannot not be instantiated, for they are pre-defined abstractions.
However in one situation, you may use 'new' followed by the interface type or abstraction class type.

When declaring an array, you may declare an interface type and abstract class type array.


import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author YNZ
 */

interface myInterface{
    void doSth();
}

class myDevice extends myAbstract implements myInterface{

    @Override
    public void doSth() {
        System.out.println("my device do something!");
    }
}

abstract class myAbstract{
    abstract public void doSth();
}

public class InterfaceArray {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       myInterface[] is = new myInterface[3];
       is[0] = new myDevice();
       is[1] = new myDevice();
       is[2] = new myDevice();
       
       List[] ls = new List[4];
       ls[1] = new ArrayList();
       ls[4] = new ArrayList();
       
       myAbstract[] as = new myAbstract[2];
       as[0] = new myDevice();
       as[1] = new myDevice();
    }
    
}


Saturday, 18 June 2016

OOAD: Overloading



The purpose of overloading is to re-use the method signature. 

Overload Methods

Overloading is distinguished and validated only by input augment lists. 

  • The change in the number of parameters that are accepted.
  • The change in the type of method parameters that are accepted.
  • The change in the positions of the parameters that are accepted
public void method(float m1, int m2){}
public void method(int m2, float m1){}

The sequence of parameters can create different argument lists, so it is valid overloading. 

Overloading methods cannot be validated by differing return types. 
double calcAverage(int m1, int m2){}
int calcAverage(int m1, int m2){}
the above is invalid overloading and leading to a compiling error. 

Overloading methods cannot be validated by differing access modifiers
Overloading method cannot be validated by differing non-access modifiers


When the class don't share an inheritance relationship, there isn't any confusion with the version of the method that will be called. 

Class Base{}
Class A extends Base{}
Class B extends Base{}

A and B they both in a different branch of the inheritance tree, they are not a confusion;
However, A and Base are on the same inheritance branch; they may create confusion. 
A is a Base; while Base is also Base;  These two types may confusing the overloading. 

Class Reception{
public void accept(Base var){} //1
public void accept(A var){}//2
}

If invoking accept(new A()); Which overloading method will be called?
here the A instance is created, so //2 should be invoked. 

The overloaded methods are bound at the compiling time but not runtime. 

In another way: 
Base a = new A();
accept(a)

On the compiling time, a is considered as a Base class type because of the reference variable type, the //1 is therefore invoked. 


Overloaded Constructors

  • Overloaded Constructor must be defined using a different argument list. 
  • Overloaded Constructors cannot be validated by differing only the access modifiers. 
Using this key to refer to other overloaded constructors in a constructor; it is a common mistake to use a Class name to refer to other overloaded constructors in a constructor. 

Using non-access modifiers with constructors is illegal. The code won't compile. 



In the following case, imagine what will the output?
/**
 *
 * @author YNZ
 */
class TestClass {

    void probe(int... x) {
        System.out.println("In ...");
    } //1

    void probe(Integer x) {
        System.out.println("In Integer");
    } //2

    void probe(long x) {
        System.out.println("In long");
    } //3

    void probe(Long x) {
        System.out.println("In LONG");
    } //4

    void probe(Object x) {
        System.out.println("In Object");
    } //5

    void probe(int x) {
        System.out.println("In int");
    } //6

    public static void main(String[] args) {
        Integer a = 4;
        new TestClass().probe(a); //5
        Long b = 4L;
        new TestClass().probe(b); //6
        byte c = 100;
        new TestClass().probe(c);
        char d = 'a';
        new TestClass().probe(d);
        int e = 10;
        new TestClass().probe(e);
        String str ="aha";
        new TestClass().probe(str);
        int[] array = new int[3];
        new TestClass().probe(array);
        

    }
}



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...