笔记整理

1, Stack, heap, contructor

Stack: method invocations, local variables

所以在eclipse里查看stack trace,最上面的是当前调用的方法,当结束当前方法,其就会被移出stack.

variable: primitive, or non-primitive:Object

注意local variable如果是reference to object, stack只会存放reference,真正的object还是会在heap里面。

Heap: ALL objects[including instance variable]

instance variable不同于local var, 它是定义在class里,method外的变量。Default value of instance var: primitive 0/0.0/false, Reference null.

例如:在cellphone class里定义有instance variable Ant, 在cellphone object自己所占的堆空间中并不会存有Antenna object的,只会寸它的ref ant.

class Cellphone{ private Antenna ant = new Antenna(); //将object同ref连接起来

Constructor:

当自己不定义任何constructor时,compiler才会帮忙提供一个无参数的constructor。自己可以定义多个,有参+无参,overloaded constructor之间可用this(...)调用, 或者用new Bunnies(5)也可以。

constructor和method的区别是没有return type. constructor不可以继承,一定要明确调用父类的constructor。

constructor chaining: 子类在实例化的时候一定要一层层往上调用父类的constructor. 例如stack最上面是Object(), Animal(), 最下面是Hippo()。super()也可以有参数。调用父类的方法用super.method()。

在一个constructor里面不可以同时call super()和this(...).

Variable life: 

instance variable:跟object一样长。

local variable: 跟其所在的method在stack中待的时间一样长。

Reference var的life是只要Ref alive, object就alive in heap. Otherwise, abandoned by heap, reachable by GC.

Life z = new Life();  //这个z引用被赋予新值,或是被设为null,那原本的object就可以被GC了。

2, Java webservice:

实现方法JAX-WS

Webservice处理数据的方式是用Schema将XML定义成标准(即wsdl), WSDL(web service discription language)规范是一个描述接口,语义及web服务为了响应请求需要经常处理的工作的文档。

UUDI利用soap消息机制(XML/HTTP):用XML格式来封装各种数据,发送到注册中心,或由注册中心返回数据。

Steps: Request XML(SOAP) -> JAXB -> JAVA object -> JAXB ->Response XML(SOAP)

JDK中的wsimport是个工具,用来根据wsdl生成客户端代码。

小结:用java写好webservice以后,EndPoint.publish()可以将自己的webservice发布。在客户端,用wsimport生成webservice的客户端代码(生成的启动需要指明webservice的URL),然后就可以调用了。

JAXB: Java architecture for XML binding.

JAXB包括"xjc"工具:XML->JAVA, "schemagen"工具: JAVA->XML[JAXBContent:Marshaller].

3, Java advantage

Java的优点: friendly syntax, object-oriented features, memory management, portability.

Portability是指:Javac compile过的byte code是platform-independent的,只要平台上有VM就可以读取bytecode运行。

Java的起点:public static void main(String[] args)

4, Serialization

序列化可以将object保存起来,之后可以被java program读取。

Object ---> OjbectOutputStream(Chain stream) ---is chained to---> 0110001010(FileOutputStream, ConnectionStream) ---> file

FileOutputStream fileStream = new FileOutputStream("M.ser");

ObjectOutputStream os = new ObjectOutputStream(fielStream);

os.writeObject(01);

os.close();

保存object的意思是:保存了所有member的value, 如果instance variable指向其它object,它们也会被序列化。保存object的前提是这个object要implement Serializable Interface。保存object的时候可以选择只保存一部分变量: 用transient keyword,可令变量被skip。

Deserialization process: File->FileInputStream->ObjectInputStream->Object.

对于读写text file,可用FileWriter:

FileWriter writer = new FileWriter("Foo.txt"); writer.write("hello!");  writer.close();

要提高efficiency,可用BufferWriter,因为FileWriter每次写个String都会放到Disk的File里。用BufferedWriter,可以将String放入Buffer,Buffer满了再入File.

Object的class implements Serializable,有用到SerialVersionUID,这个UID是根据当前class算出来的,当Object被Desirialized时,这个ID会与JVM用的class的ID比较,相等才可以。

5,Java Numbers & Statics

Math.round()这些Math的methods都是static方法,所以不用Math类的Object即可使用。

使类不能实例化: Abstract class/private constructor.

final的作用:variable不能改值,method不能被override,class不能被继承。

primitive type:例如int, double,不是Object, 当需要Object时,可以将其wrap为Integer, Double, Character...这样就可以有null value,或作为Generic type。

两者可以自动转换,这些Integer/Double class的好处是提供了String和int, double...之间的转换方式:

int x = Integer.parseInt("2"); //Can throw NumberFormatException, runtime的

String y = Integer.toString(x);

6, Generic method: 

public class ArrayList<E> extends AbstractList<E> ...{  

  public boolean add(E o);

public <T extends Animal> boolean add(ArrayList<T> list)

7, Same object

得是.hashcode()相同,或是.equals()成立。

HashCode是Java给Object基于Object's memory address on the heap. 所以没有两个object是相同的hashcode,但你可以override它。最好是当你的class是value object的时候,(即值相等,物体即可相等),才有需要override .equals()方法。

I1: Static factory methods:

除了用constructor构建object外,就是用static factory method了。优点:method name可以设计的更易懂, 不必每次call都生成新的object,Return type可以不必是当前class本身而是其subclass(例如Collections全都是static methods返回其它Collection class).

a, valueOf(param) 返回与param相同值的class instance.

b, getInstance 包括Singleton

c, newInstance 保证返回的instance与其它的都不同

I2: 针对太多constructor params的Builder方法

当一个class有太多params给constructor/static factory的时候,选择Builder pattern是好的。

public class A{

  private final int a1, a2...

  public static class Builder{

    private final int a1, a2...

    public Builder(int a1, int a2) {this.a1 = a1; this.a2= a2;}

可选的   public Builder a3(int a3)       {this.a3=a3;return this;}

    ...

  }

  private A(Builder builder)     {a1 = Builder.a1; a2 = Builder.a2;...}

}

I3: Singleton:

1, public class A{

  public static final A INSTANCE = new A();

  private A() {...}

}

用public static final field A.INSTANCE.

2,用static factory method.

public class A{

  private static final A INSTANCE = new A();

  private A() {...}

  public static A getInstance() { return INSTANCE;}

}

I4:有时你会需要设计class只包含一堆static methods, static fields, 这种class不是被instantiated的,有instance不合理,所以可以用private constructor.

I5: 

An Object can always be reused if it is immutable. 例如String s = "stringette";每次执行时,不会重新建立新的,但是String s = new String("stringette");会建立新的

By using factory methods on immutable classes: 例如Boolean.valueOf(String)就不会建新的,而Boolean(String) constructor会建立新的。

Reuse mutable objects if you know they won't be modified.例如一个class A里的isBabyBoomer()方法里有建立新的Calendar Date objects, 它们也不会被改变,每次call时都一样,就可以把它们拿出来放在class A里Static{   }里面。

Prefer primitives to boxed primitives, and watch out for un-intentional autoboxing. 

I6: 防止内存泄露

1,当class manages its own memory:

Whenver an element is freed, any object references contained in the element should be nulled out.

例如stack pop element的时候,其实stack还对那些element有obsolete references,GC无法回收它们

public Object pop() {

  if(size==0) throw new EmptyStackException();

  Object result = elements[--size];

  element[size]=null;

  return result;

}

2,当put an object reference into a cache, 容易把它忘在那里

3, Listeners and callbacks

I8: General contracts when overriding equals

如果类的每个实例都是与众不同、独一无二的,那么Object原本的.equals()就够了.

但对于value class, 需要用逻辑相等来override equals().

I13: MINIMIZE ACCESSIBILITY OF CLASSES/MEMBERS

1, package-private还是public?

如果可以package private就pp, 弄成public就要考虑client方,要maintain它.

2, nested or non-nested?

如果你的class只被另一个class使用,让它成为private nested class,这样它的accessibility就只在一个class中,不被package其它class使用

3, member的accessibility

除了明确指明private, public, protected以外,不指明的话by default就是package private,一般情况下最好指明private,如果有同package里的其它class需要用就另其为package private.

4, Interface的method都是implicitly public

5, public class should have no public fields

除了public static final FIELD: 而且这个field得是primitive or immutable的。因为如果你的FIELD是Array或Reference to mutable object, 那么外界就可以改这个FIELD.

I14: Use accessor methods in public classes

在public class中,最好不要public field, 除非是public final primitive or immutable. 那么对non-final fields, 外界如何读到它们呢?用getter方法.

在package-private或private nested class中,可以选择不用getter,直接另其它某些class读到. 即使要改representation,都不用管client, 在自己的package/class里改即可。

I15: Minimize mutability

Immutable class的意思是就是这种class的instance不能被修改,每个instance里的信息在创建这个instance的时候就定好了.

五条规则 to make a class immutable:

a, No methods that modify the object's state.

b, Ensure the class not be extended.

c, Make all fields final.

d, Make all fields private.

e, Ensure exclusive access to any mutable components.

public MyDiary(Date aDate){this.myDate=new Date(aDate.getTime();}

public Date getDate() {return new Date(myDate.getTime());}

Immutable objects是inherently thread-safe的,不需要同步,如果一个thread正使用Immutable object,另一个thread是不可能看到这个object的

如果class不能成为Immutable,那么limit its mutability,让每个field final除非必需时nonfinal.

I16: Favor composition over Inheritance

OK安全: subclass and superclass implementation are within same package. 而且subclass真的是superclass的一个subtype.

不OK: across package.

继承的问题:当subclass override super-class method1, the method1 calls super method2, 这个super.method2()如果也被overriden了,那就又调用的sub-class的方法,这种控制很复杂.

而且sub-class无法控制super class,例如super加了一个新的方法,sub-class调用起来可能不是sub想要的.

Example:

原public class InstrumentedHashSet<E> extends HashSet<E>

现public class InstrumentedHashSet<E> extends ForwardingSet<E>

   public class ForwardingSet<E> implements Set<E> {

    private final Set<E> s;

    public int size() {return s.size();}

    public boolean add(E e) {return s.add(e); }

}

I17: Design and Document for Inheritance/Prohibit

什么时候需要继承?

当sub-class真的是parent的子类别/当需要为这个类添加: instrumentation/notification/synchronization/limitfunctionality

什么需要Document?

比如AbstractCollection类里的public boolean remove(Object o), 在说明就有提到这个remove方法里有调用overridable method. 因为这种method如果被子类重写了,那么super constructor先于子类constructor,而反回来call sub-class的method, 而这个method有可能于子类的constructor有关.

public class Super{ public Super() { overrideMe(); }   public void overrideMe(); }

I18: Prefer INTERFACE to abstract class

两者的区别: Abstract class可以实现一些方法, 一个类要想实现,必须extend Abstract class,由于java只允许single inheritance,这就造成限制。而interface则可以实现多个.

Implement interface: defining mixins, allow construction of nonhierachical type framework.

abstract skeletal implementation class: 例如AbstractSet...你可以extend这个skeletal class,或者直接implement interface。这个的好处是,如果你填加一个方法,只改interface,那么所有实现这个interface的类都会出compilation error。而如果改skeletal implementation class+interface,那么extend这个skeletal的sub-class就不会受到影响.

I19: Use Interface only to define types

用interface,只为了给class去implement,不要有只包含static final fields的constant interface.

因为如果class implement这种constant interface, 那么exported API都会有这些constant fields,会误解client.

所以,如果你想export constant,可以将它们直接加入class or enum type,或使用utility class.

utility class example:

public class PhysicalConstants{  

  private PhysicalConstants(){}

  public static final double AVOGADROS_NUMBER=6.022;

  public static final double ELECTRON_MASS=9.1093;...

}

这样在用到的地方,直接import static这个class就可以了。

20141029 虽然被打击了一下,但我还撑得住,不会被这点小挫折打败,有失必有得,在前进的道路上,是我想要的,我一定会努力,笑对人生。我能做的就是抛下失落,积极向前,做我能做的增加成功的机率。Fighting baby!Fighting baby!

原文地址:https://www.cnblogs.com/chayu3/p/4049449.html