您的位置:首页 > 其它

多态、继承---常量的覆盖和方法的重写

2015-02-03 09:36 381 查看
代码如下:
package pkginterface.inheritance;
public class InterfaceInheritance {
public static void main(String[] args) {
Operator[] array={new P1(),new P2(),new P3(),new P4(),new P5(),new P6()};   //多态的一种体现
for(int i=0;i<array.length;i++)
array[i].play();
}
}
interface Operator{                //接口
public static final int MODE=1;
void play();
}
class P1 implements Operator{     //实现
public void play(){System.out.println("P1 Mode-"+MODE);}
}
class P2 implements Operator{
public static final int MODE=2;
public void play(){System.out.println("P2 Mode-"+MODE);}
}
class P3 extends P1{      		  //继承
public static final int MODE=3;
}
class P4 extends P2{
public void play(){System.out.println("P4 Mode-"+MODE);}
}
class P5 implements Operator{
int MODE=5;
public void play(){System.out.println("P5 Mode-"+MODE);}
}
class P6 implements Operator{
String MODE="6";
public void play(){System.out.println("P6 Mode-"+MODE);}
}


结果:
P1 Mode-1
P2 Mode-2
P1 Mode-1
P4 Mode-2
P5 Mode-5
P6 Mode-6


出现上述结果应该明白的几个点:

1)实现接口的类,其拥有接口中定义的常量和方法的使用权限(注意:接口中不能定义私有变量)

2)继承
子类继承父类的方法和属性(不包含私有方法和私有变量)

3)方法的调用顺序
如果子类含有和父类相同的方法,先调用子类的方法,然后调用父类的方法(方法的重写)

4)static 定义的变量属于类属性,子类不进行集成

注:p3 处出现【P1 Mode-1】由于继承 p3 调用父类方法, 输出model 为1 原因是父类方法调用的是其自身的常量
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐