2013年7月8日 星期一

Java basics for newbie

Common keyword clarification:
1. Static
Two types of static members are static field and static method. The value of static field is the same across all instances of the class and that means there's only one copy of the field. One good example is to use a static field to keep track of the amount of created instances of a class. Similarly, to use a static method, one doesn't have to create an instance before using it. One basic rule is that it's invalid to use non-static members in a static method, because a static method does not even know those non-static members exist !

The below code snippet will cause compiler error:

public class ABC() {
    public String data = "123"
    
    public static void main() {
        System.out.println(data);
    }
}

instead, use the following way to access a non-static member from static method:

public class ABC() {
    public String data = "123"
    
    public static void main() {
        ABC n = new ABC();
        System.out.println(n.data);
    }
}

2. Visibility keywords - public, private, protected, no modifier(default)

Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N

Class: within the same class
Package: within the same package
no modifier(default): package-private, within the same package
World: among different packages

Tips about choosing access level on a class/member:
1. Use the most restrictive level that makes sense for a particular class/member. Use private unless you have a good reason not to.
2. Avoid using public except for constants.

3. final
final class: once declared as final, the class can not be extended by other classes
final method: a final method can not be overridden by subclasses
final member: a final variable can only be assigned once when either in a initializer or through an assignment statement before constructor is done with its job.

Reference
http://www.dummies.com/how-to/content/what-is-the-static-keyword-in-java.html
http://www.javacoffeebreak.com/articles/toptenerrors.html
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
http://en.wikipedia.org/wiki/Final_%28Java%29

沒有留言:

張貼留言