【发布时间】:2017-09-08 04:30:33
【问题描述】:
我想知道。当我有两个类而第二个类metalRobot 扩展了第一个类robot 时,有没有办法在第二个方法中调用第一个类的方法来覆盖它?
示例
//super class
class robot{
private int width;
private int height;
//constructor
robot(int width,int height){
this.width=height;
this.width=height;
}
//display width and height
void render()
{
System.out.println(width + " " + height);
}
}
//child class
class metalRobot{
private int x;
private int y;
//constructor
metalRobot(int x,int y, int height, int width){
super(width,height);
this.x=x;
this.y=y;
}
@Override
void render()
{
System.out.println(x + " " + y);
}
}
所以当我调用渲染时,它会打印出 x,y 宽度和高度
【问题讨论】:
-
您的
metalRobot需要扩展robot类,否则它不是子类。 -
Java 中的类名,按照惯例,应该使用大写。
-
在教学时,我告诉我的学生,当我看到一个不包含
super调用的覆盖方法时,我通常会怀疑,例如super.render();。
标签: java polymorphism overriding