final是java中的一个关键字,以前一直以为C++中没有这个关键字,刚刚查了一下,竟!然!也!有!好像用法也差不多。
大致分为这么几种,被这个东西修饰过的东东,到此为止了,也不能被改动了。
比如说
1 函数被修饰的话,不能被重写覆盖
2 类被修饰的话,不能被继承
3 变量被修饰的话,只能被赋值一次,记住哦,这个和C++中的 static const是不一样的,这个玩意可以先声明,不一定要声明时赋值,但 只!能!赋!值!一!次!。
上代码
final class Animal{ //这里加的话,下面那个继承会报错哦
public final int ff; //就是这里哦
{
ff= 4; //可以用代码块赋值
}
public Animal(int t) {
// this.ff= t;//也可以用构造函数赋值
System.out.println("create animal");// TODO Auto-generated constructor stub
}
public final void cry(){//这里加的话,下面那个覆盖也不行了鸟
System.out.println("wo~~~~~~~");
}
public final void run(){//但是别忘了,虽然不能被重写,但是用还是可以凑合用的
System.out.println("runrunrunrunr");
}
}
class Dog extends Animal{
public Dog(int t) {
super(t);
System.out.println("create dog");// TODO Auto-generated constructor stub
}
public void cry(){
run();
System.out.println("wang~~~~~~"+ff);
}
}
class Test{
public static void main(String[] args){
Dog dog = new Dog(3);
dog.cry();
Dog dog2 = new Dog(5);
dog2.cry();
}
}
就是这样,其他的
原文:http://www.cnblogs.com/mulog/p/5699673.html