【发布时间】:2016-10-03 08:10:27
【问题描述】:
请原谅我的问题,因为我试图搜索使用 super 关键字与类名从超类调用方法之间的区别,但无法找到答案。 我的问题是我正在尝试将 Java 作为一门学习课程来学习,并且正在使用链接中的一个示例:http://www.javatpoint.com/super-keyword using Example # 3,这是我编写的代码:
我创建了一个名为 Vehicle 的超类
public class Vehicle {
Vehicle() {
System.out.println("Vehicle constructor created");
}
public void speed() {
int a = 20;
System.out.println(a);
}
}
然后使用以下代码创建了一个名为 Bike 的子类:
public class Bike extends Vehicle {
int speed;
Bike(int speed1) {
this.speed = speed1;
System.out.println(speed1);
super.speed();
}
public static void main(String args[]) {
Bike b = new Bike(10);
}
}
在 Bike 构造函数下的子类中,我使用 super.speed() 从 super (Vehicle) 类调用 speed 方法。现在,如果我将此行更改为 Vehicle.speed() 我会收到一条错误消息,指出我需要将我的速度方法设为静态。
我不想让我的方法是静态的,想知道它们之间的区别。
干杯,
【问题讨论】:
-
我认为原因是如果您使用 class.method 名称,它是以静态方式访问该方法。但我不是 100% 确定这一点。所以只是评论:)
-
如果您将其更改为 this.speed(),恕我直言,它应该可以工作 :)
标签: java methods constructor super