difference between Interface and abstract class in Java

来源:互联网 发布:少年包青天1抄袭 知乎 编辑:程序博客网 时间:2024/06/05 03:57
  •  one class can ony extends one super class, but can implements multiple interfaces

 

  •  abstract class can have codes:
    • class/instance field proper value initilizers
    • instance initilizers
    • class initilizers

 

  • interface can have only codes:
    • class field proper value initilizers

 

  • Superclasses need to be initialized before subclasses, so these classes are likely already loaded. Superinterfaces do not need to be initialized when a class that implements them is initialized. However, superinterfaces must be loaded when the class that implements them (or the interface that extends them) is loaded. (They won't be initialized, just loaded and possibly linked at the option of the virtual machine implementation.) All a class's supertypes will be loaded when the class is loaded.

 

  • Interfaces may also be awarded a () method in the class file. All fields declared in an interface are implicitly public, static, and final and must be initialized with a field initializer. If an interface has any field initializers that don't resolve at compile-time to a constant, that interface will have a (cinit) method.  But we cannot have an explicit class initilizer block for it

 

The Java compiler generates at least one instance initialization method for every class it compiles. In the Java class file, the instance initialization method is named "<init>." For each constructor in the source code of a class, the Java compiler generates one <init>() method. If the class declares no constructors explicitly, the compiler generates a default no-arg constructor that just invokes the superclass's no-arg constructor. As with any other constructor, the compiler creates an <init>() method in the class file that corresponds to this default constructor.

 

In Java programs, classes can be instantiated explicitly or implicitly. The four ways a class can be instantiated explicitly are

  1. with the new operator,
  2. by invoking newInstance()on a Class or java.lang.reflect.Constructor object,
  3.  by invoking clone() on any existing object,
  4. or by deserializing an object via the getObject() method of classjava.io.ObjectInputStream.

new operator and newInstance() will call respondent init() methods, other ways will not.

http://www.artima.com/insidejvm/ed2/lifetypeP.html