关于接口,一个一直不确定的问题就是它到底能不能拥有字段,下面的代码回答:可以。
由此引出有意思的一点是,java 中,接口的字段居然是默认的会以 public final static 修饰,何以如此?见代码注释。
- 其实最精髓的就是把握Java中接口的设计原则:它更像一种契约,白纸黑字,无可更改。
- 至于抽象类,它和普通类的唯一本质区别,在我看来,就是它可以包含无方法体的抽象方法,而由此,也导致它不能直接实例化。
- 至于两者的区别,上面谈到的字段算一个,其实最本质的我感觉还是设计理念不同,一个很好的说法是 接口 是用来代表Can Do 的,而 抽象类 则是 is a. 超人和鸭子都Can fly,但两者显然非同一物种。所以好的做法是 两者都实现Fly 接口,而鸭子,还是和鸡啊鹅啊什么的去一起继承自 禽 这一抽象类吧。
- 接口
/**
* 1.can interface have fields? yes,but it is [public final and static] by
* default.
*
* Interface is like an contract,class who have used it must follow it. so it is
* important that the contract is quite stable(or immutable),
*
* so the fields is final(can not be changed) and static(every one
* has the same copy of it,no one is different).
*
* while,it is also public(if it is private,what does it used for? It is
* useless).
*
* @author mmLiu
*
*/
public interface myInterface {
public final static int filed1 = 1;
}
- 抽象类
/**
* I think the only essential difference between abstract class and normal class
* is that the abstract one can have unimplemented method(so called abstract
* method).
* <p>
* and As a result,it can not be initialized.
*
* @author mmLiu
*
*/
public abstract class myAbstractClass {
int myInt;
/**
* Constructor
*/
public myAbstractClass() {
System.out.println("Parent's Constructor");
}
/**
* Abstract method does not have method body(otherwise how can it be called
* abstract?).
* <p>
* while ,an abstract class does not have to have an abstract method.you can
* safely remove this method,it is still right.
*
* @param a
* @return
*/
public abstract int myVirtualMethod(int a);
public int myMethod2(int a) {
return a;
}
}
ps.关于这种文章主体存在于代码中的写作方式,我承认是因为我懒,我自己都很怀疑这样的文章,除对我存在可读性外,是否还能有他人,但考虑到我的博客会不会真的居然还会有读者,所以,让我懒下去吧。