{Java Detail} Interface and Abstract Class

关于接口,一个一直不确定的问题就是它到底能不能拥有字段,下面的代码回答:可以。

 

由此引出有意思的一点是,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.关于这种文章主体存在于代码中的写作方式,我承认是因为我懒,我自己都很怀疑这样的文章,除对我存在可读性外,是否还能有他人,但考虑到我的博客会不会真的居然还会有读者,所以,让我懒下去吧。

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值