java中的向上转型我们已经很熟悉,接下来我们将实现public static final属性,向上转型以及抽象类的使用。
向上转型:
父类:class Father{}
子类:class Son extends Father{}
Father f1 = new Son();//向上转型
Son s1 = (Son)f1;//向下转型
由此我们的疑问出现了。那么我们为什么不这样写呢?
Father f1 = new Father();
Son s1 = (Son)f1;
这样写ide会报错:
这篇优秀的bolg解释了为什么
http://blog.csdn.net/mr_jj_lian/article/details/6860845
final在java中被称为终结器,使用了final定义的变量就意味着这个变量成为了常量。
package head_first;
abstract class Action{
public static final int EAT = 1;
public static final int SLEEP = 2;
public static final int WORK = 4;
public void command(int flag) {
switch(flag) {
case EAT:
this.eat();
break;
case SLEEP:
this.sleep();
break;
case WORK:
this.work();
break;
case EAT+WORK:
this.eat();
this.work();
break;
}
}
public abstract void eat();
public abstract void work();
public abstract void sleep();
}
class Robot extends Action{
public void eat() {
System.out.println("eat");
}
public void work() {
System.out.println("work");
}
public void sleep() {
}
}
class Human extends Action{
public void eat() {
System.out.println("eat");
}
public void work() {
System.out.println("work");
}
public void sleep() {
System.out.println("sleep");
}
}
class Pig extends Action{
public void eat() {
System.out.println("eat");
}
public void work() {
}
public void sleep() {
System.out.println("sleep");
}
}
public class Exp446 {
public static void main(String[] args) {
// TODO Auto-generated method stub
fun(new Robot());
fun(new Human());
fun(new Pig());
}
public static void fun(Action act) {
act.command(Action.EAT);
act.command(Action.WORK);
act.command(Action.SLEEP);
}
}
我们看到关键的代码:
abstract class Action
//抽象类
class Robot extends Action
//实例化
fun(new Robot());
public static fun(Action act);
//向上转型
public static final int EAT = 1;
//static使得它可以在mian方法中使用