Friday, November 30, 2012

What does the final modifier mean on a method parameter?



What does the final modifier mean on a method parameter?

Use the final modifier on formal parameters to methods when you want to make it clear that the supplied value can be not modified inside the method. The compiler would complain as soon as you accidentally try to assign it a new value inside the method. Anonymous classes that need to access method's parameters are another use case of final method parameters.
  • The final keyword on instance and local variables of primitives type only makes primitives behave like constants. You can not reassign value to them.
  • The final keyword on a reference variable only restricts the reference itself can not be changed but you still can change the context of the object that the reference points to.
  • The final keyword on a formal parameter restricts the formal parameter can not be reassigned inside the method. The final keyword is not part of the method's signature, it can be removed from its overriding method in its subclass.

Only final variables accessible in anonymous class.
interface Worker { void perform_work(); }
Worker getWorker(final int i){ 
class MyWorker implements Worker 
{
public void perform_work() 
System.out.println(i); 
}
};
return new MyWorker();
}

Constructor


Constructors

When you create a new instance (a new object) of a class using the new keyword, a constructor for that class is called. Constructors are used to initialize the instance variables (fields) of an object. Constructors are similar to methods, but with some important differences.
  • Constructor name is class name. A constructors must have the same name as the class its in.
  • Default constructor. If you don't define a constructor for a class, a default parameterless constructor is automatically created by the compiler. The default constructor calls the default parent constructor (super()) and initializes all instance variables to default value (zero for numeric types, null for object references, and false for booleans).
  • Default constructor is created only if there are no constructors. If you define any constructor for your class, no default constructor is automatically created.
  • Differences between methods and constructors.
    • There is no return type given in a constructor signature (header). The value is this object itself so there is no need to indicate a return value.
    • There is no return statement in the body of the constructor.
    • The first line of a constructor must either be a call on another constructor in the same class (usingthis), or a call on the superclass constructor (using super). If the first line is neither of these, the compiler automatically inserts a call to the parameterless super class constructor.
    These differences in syntax between a constructor and method are sometimes hard to see when looking at the source. It would have been better to have had a keyword to clearly mark constructors as some languages do.
  • this(...) - Calls another constructor in same class. Often a constructor with few parameters will call a constructor with more parameters, giving default values for the missing parameters. Use this to call other constructors in the same class.
  • super(...). Use super to call a constructor in a parent class. Calling the constructor for the superclass must be the first statement in the body of a constructor. If you are satisfied with the default constructor in the superclass, there is no need to make a call to it because it will be supplied automatically.

Example of explicit this constructor call

public class Point {
    int m_x;
    int m_y;

    //============ Constructor
    public Point(int x, int y) {
        m_x = x;
        m_y = y;
    }

    //============ Parameterless default constructor
    public Point() {
        this(0, 0);  // Calls other constructor.
    }
    . . .
}

super(...) - The superclass (parent) constructor

An object has the fields of its own class plus all fields of its parent class, grandparent class, all the way up to the root class Object. It's necessary to initialize all fields, therefore all constructors must be called! The Java compiler automatically inserts the necessary constructor calls in the process of constructor chaining, or you can do it explicitly.
The Java compiler inserts a call to the parent constructor (super) if you don't have a constructor call as the first statement of you constructor. The following is the equivalent of the constuctor above.
    //============ Constructor (same as in above example)
    public Point(int x, int y) {
        super();  // Automatically done if you don't call constructor here.
        m_x = x;
        m_y = y;
    }

Why you might want to call super explicitly

Normally, you won't need to call the constructor for your parent class because it's automatically generated, but there are two cases where this is necessary.
  1. You want to call a parent constructor which has parameters (the automatically generated superconstructor call has no parameters).
  2. There is no parameterless parent constructor because only constructors with parameters are defined in the parent class.


Java-This


Definition for java this keyword:
Java this keyword is used to refer the current instance of the method on which it is used.

Following are the ways to use java this

1) To specifically denote that the instance variable is used instead of static or local variable.That is,
private String javaFAQ;
void methodName(String javaFAQ) {
this.javaFAQ = javaFAQ;
}
Here this refers to the instance variable. Here the precedence is high for the local variable. Therefore the absence of the “this” denotes the local variable. If the local variable that is parameter’s name is not same as instance variable then irrespective of this is used or not it denotes the instance variable.
2) Java This is used to refer the constructors
public JavaQuestions(String javapapers) {
this(javapapers, true);
}
Java This invokes the constructor of the same java class which has two parameters.
3) Java This is used to pass the current java instance as parameter
obj.itIsMe(this);
4) Similar to the above, java this can also be used to return the current instance
CurrentClassName startMethod() {
return this;
}
Note: This may lead to undesired results while used in inner classes in the above two points. Since this will refer to theinner class and not the outer instance.
5) Java This can be used to get the handle of the current class
Class className = this.getClass(); // this methodology is preferable in java
Though this can be done by, Class className = ABC.class; // here ABC refers to the class name and you need to know that!
As always, java this is associated with its instance and this will not work in static methods.

http://stackoverflow.com/questions/4394976/what-is-the-difference-between-synchronizedthis-and-synchronized-method
Question:

Lets say we have these 2 sample code :
public synchronized void getSomething(){
     this.hello = "hello World";
}
and this one
public void getSomething(){
   synchronized(this){
     this.hello = "hello World";
   }
}
So some one can tell me what's the difference now?
Answer:




In the code presented, there is no functional difference. There may be a very small performancedifference:
At the bytecode level, the synchronized method advertises its need for synchronization as a bit set in the method's access flag. The JVM looks for this bit flag and synchronizes appropriately.
The synchronized block implements its synchronization through a number of bytecode operations stored in the class file's definition of the method.
So the synchronized method should execute ever so slightly faster and take up less space in terms of bytecode.
Again, the two are, by specification, functionally identical.
I'm guessing that the performance difference is probably negligible for most applications.





Thursday, November 29, 2012

Java-Javabeans

What s JavaBean?
http://zhidao.baidu.com/question/51726153.html

Wednesday, November 28, 2012

11/28/2012 - present

1. Why prefer composition to inheritance?


2. Anonymous Inner Class has the same name, say ClassA, with a class - ClassA means this anonymous class is the subclass of ClassA .


3. synchronized keyword can only be applied to a method or a block.
not even a class or a data field!!!!!


4. every subclass must call either super() or super(someparameters) explicitly,
otherwise super(); will be added to the first line of subclass constructor by compiler.

EX:

package b;
import a.A;

public class B extends A{
B(int i)
{
super(i); //call super(i) explicitly, otherwise, super() would be called.
System.out.println("B");
}
public static void main(String[] args){
new B(1);
}
}
--------------------------------------------------------

package a;
public class A{
A( ){System.out.println("A");}
// (default) only accessible within the same package. So, if B didn't call super(i) explicitly, super(); would be called and then compile error would occur.
protected A(int a)
{
System.out.println("aA");
}
public void  print()
{
System.out.println("A");
}
}

Result:
aA
B

5. The return type should be same for overridden and overriding method.
Having the same signature is not enough for overriding. Return type must be the same.

Overriding:  same-return-type same-method-Name (same-parameters) {}

Overloading:  same-method-name (){}

public void  print()
{
System.out.println("A");
}
int print(int i)
{
return i;
}

Inheritance
1. Remember : variables are SHADOWED and methods are OVERRIDDEN.
Which variable will be used depends on the class that the variable is declared of.
Which method will be used depends on the actual class of the object that is referenced by the variable.  


2. instanceof
if(a instanceof B)
to use instanceof a,B must be compatible, which means that the actual type of a, say A, either extends B or implements B or is B, otherwise, compile error will occur.
c instanceof Interf 在c不为final的情况下可以是compatible的, 因为c的subclass可能会implements Interf. 但是不可能extends B了 因为只能extends一个.


3.  Fields in an interface are implicitly public, static and final. Although you can put these words in the interface definition but it is not a good practice to do so.  

4.  Having ambiguous fields or methods does not cause any problems by itself but referring to such fields/methods in an ambiguous way will cause a compile time error
        What, if anything, is wrong with the following code?
// Filename: TestClass.java
class TestClass implements T1, T2{
   public void m1(){}
}
interface T1{
   int VALUE = 1;
   void m1();
}
interface T2{
   int VALUE = 2;
   void m1();
}
//it can be compiled
//TestClass tc = new TestClass();
//System.out.println(( ( T1) tc).VALUE); 
// tc.m1() is also fine because even though m1() is declared in both the interfaces, the definition to both resolves unambiguously to only one m1(), which is defined in TestClass.  

5. There is no construct like super.super. So, there is no way you can access m1() of A from C.   //even you cast c to A, you still call the method1 in C. 

class A{
   public void m1() {   }
}
class B extends A{
   public void m1() {   }
}
class C extends B{
   public void m1(){
   }
    public static void main(String...args)
 {
  C c =new C();
  System.out.print(c.method1());
  System.out.print(((A)c).method1());//even you cast c to A, you still call the method1 in C.
 }
}

6. A class cannot override the super class's constructor.
Because constructors are not inherited.

7. Interface cannot "implement" anything. It can extend multiple interfaces. The following is a valid declaration : 
interface I1 extends I2, I3, I4 { }

8. Keep in mind that static methods are not overridden, they are shadowed.
In computer programmingvariable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope. This outer variable is said to be shadowed.

9. Order of initiation of an instance
1. Static blocks of the base class (only once, in the order they appear in the class).

2. Static blocks of the class.

3. Non-static blocks of the base class.

4. Constructor of the base class.

5. Non-static blocks of the class.

6. Constructor of the class.

7. Derived class's static or non-static blocks are not executed if that class is not being used.




Monday, November 26, 2012

Enum


DK1.5引入了新的类型——枚举。在 Java 中它虽然算个“小”功能,却给我的开发带来了“大”方便。

用法一:常量

在JDK1.5 之前,我们定义常量都是: publicstaticfianl.... 。现在好了,有了枚举,可以把相关的常量分组到一个枚举类型里,而且枚举提供了比常量更多的方法。

Java代码
  1. public   enum  Color {  
  2.   RED, GREEN, BLANK, YELLOW  
  3. }  

用法二:switch

JDK1.6之前的switch语句只支持int,char,enum类型,使用枚举,能让我们的代码可读性更强。

Java代码
  1. enum  Signal {  
  2.     GREEN, YELLOW, RED  
  3. }  
  4. public   class  TrafficLight {  
  5.     Signal color = Signal.RED;  
  6.     public   void  change() {  
  7.         switch  (color) {  
  8.         case  RED:  
  9.             color = Signal.GREEN;  
  10.             break ;  
  11.         case  YELLOW:  
  12.             color = Signal.RED;  
  13.             break ;  
  14.         case  GREEN:  
  15.             color = Signal.YELLOW;  
  16.             break ;  
  17.         }  
  18.     }  
  19. }  


用法三:向枚举中添加新方法

如果打算自定义自己的方法,那么必须在enum实例序列的最后添加一个分号。而且 Java 要求必须先定义 enum实例。

Java代码
  1. public   enum  Color {  
  2.     RED("红色" ,  1 ), GREEN( "绿色" ,  2 ), BLANK( "白色" ,  3 ), YELLO( "黄色" ,  4 );  
  3.     // 成员变量   
  4.     private  String name;  
  5.     private   int  index;  
  6.     // 构造方法   
  7.     private  Color(String name,  int  index) {  
  8.         this .name = name;  
  9.         this .index = index;  
  10.     }  
  11.     // 普通方法   
  12.     public   static  String getName( int  index) {  
  13.         for  (Color c : Color.values()) {  
  14.             if  (c.getIndex() == index) {  
  15.                 return  c.name;  
  16.             }  
  17.         }  
  18.         return   null ;  
  19.     }  
  20.     // get set 方法   
  21.     public  String getName() {  
  22.         return  name;  
  23.     }  
  24.     public   void  setName(String name) {  
  25.         this .name = name;  
  26.     }  
  27.     public   int  getIndex() {  
  28.         return  index;  
  29.     }  
  30.     public   void  setIndex( int  index) {  
  31.         this .index = index;  
  32.     }  
  33. }  


用法四:覆盖枚举的方法

下面给出一个toString()方法覆盖的例子。

Java代码
  1. public   enum  Color {  
  2.     RED("红色" ,  1 ), GREEN( "绿色" ,  2 ), BLANK( "白色" ,  3 ), YELLO( "黄色" ,  4 );  
  3.     // 成员变量   
  4.     private  String name;  
  5.     private   int  index;  
  6.     // 构造方法   
  7.     private  Color(String name,  int  index) {  
  8.         this .name = name;  
  9.         this .index = index;  
  10.     }  
  11.     //覆盖方法   
  12.     @Override   
  13.     public  String toString() {  
  14.         return   this .index+ "_" + this .name;  
  15.     }  
  16. }  

用法五:实现接口

所有的枚举都继承自java.lang.Enum类。由于Java 不支持多继承,所以枚举对象不能再继承其他类。

Java代码
  1. public   interface  Behaviour {  
  2.     void  print();  
  3.     String getInfo();  
  4. }  
  5. public   enum  Color  implements  Behaviour{  
  6.     RED("红色" ,  1 ), GREEN( "绿色" ,  2 ), BLANK( "白色" ,  3 ), YELLO( "黄色" ,  4 );  
  7.     // 成员变量   
  8.     private  String name;  
  9.     private   int  index;  
  10.     // 构造方法   
  11.     private  Color(String name,  int  index) {  
  12.         this .name = name;  
  13.         this .index = index;  
  14.     }  
  15. //接口方法   
  16.     @Override   
  17.     public  String getInfo() {  
  18.         return   this .name;  
  19.     }  
  20.     //接口方法   
  21.     @Override   
  22.     public   void  print() {  
  23.         System.out.println(this .index+ ":" + this .name);  
  24.     }  
  25. }  

用法六:使用接口组织枚举


Java代码
  1. public   interface  Food {  
  2.     enum  Coffee  implements  Food{  
  3.         BLACK_COFFEE,DECAF_COFFEE,LATTE,CAPPUCCINO  
  4.     }  
  5.     enum  Dessert  implements  Food{  
  6.         FRUIT, CAKE, GELATO  
  7.     }  
  8. }  

用法七:关于枚举集合的使用

java.util.EnumSet和java.util.EnumMap是两个枚举集合。EnumSet保证集合中的元素不重复;EnumMap中的 key是enum类型,而value则可以是任意类型。关于这个两个集合的使用就不在这里赘述,可以参考JDK文档。
关于枚举的实现细节和原理请参考: