我正在尝试满足作业要求...“至少包括一个接口,该接口至少包含实现类必须实现的一种方法。”
[当我尝试实例化该接口时,它说它无法实例化该接口。我不确定自己在做什么错。
我已经尝试了几种方法使其起作用。
//main class
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
Ford mustang = new Ford("Mustang", 135, 125);
Chevrolet camero = new Chevrolet("Camero", 202, 100);
Dodge challenger = new Dodge("Challenger", 203, 75);
Nitrous nitro = new Nitrous();//problem code
mustang.start();
camero.start();
challenger.start();
}
}
//Abstract class
public abstract class Vehicle extends Thread implements Nitrous {
private String model;
private int speed;
private int boost;
public Vehicle(String model, int speed, int boost) {
this.model = model;
this.speed = speed;
this.boost = boost;
}
public String getmodel() {
return model;
}
public void setmodel(String model) {
this.model = model;
}
public int getspeed() {
return speed;
}
public void setspeed(int speed) {
this.speed = speed;
}
public int getboost() {
return boost;
}
public void setboost(int boost) {
this.boost = boost;
}
@Override
public void run() {
try {
go();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void go() throws InterruptedException {
int trackLength = 5000;
int checkPointPassed = 0;
for (int i = 0; i < trackLength; i += (speed + boost)) {
if (checkPointPassed * 1000 < i) {
checkPointPassed++;
System.out.println("The " + this.model + " has passed check point " + checkPointPassed);
// System.out.println(nos);
Thread.sleep(10);
}
}
}
}
//subclass one of three
public class Ford extends Vehicle {
public Ford (String model, int speed, int boost) {
super(model, speed, boost);
}
@Override
public void nos() {
// TODO Auto-generated method stub
System.out.println("The cars have Nitro!");
}
}
public class Chevrolet extends Vehicle{
public Chevrolet(String model, int speed, int boost) {
// TODO Auto-generated constructor stub.
super(model, speed, boost);
}
@Override
public void nos() {
// TODO Auto-generated method stub
System.out.println("The cars have Nitro!");
}
}
public class Dodge extends Vehicle{
public Dodge(String model, int speed, int boost) {
// TODO Auto-generated constructor stub
super(model, speed, boost);
}
@Override
public void nos() {
// TODO Auto-generated method stub
System.out.println("The cars have Nitro!");
}
}
//Interface
public interface Nitrous {
public void nos();
}
这是三辆具有亚硝酸盐助力的汽车。我选择将Nitrous设置为界面。您可以在我的代码中看到我尝试了多种方法使其正常工作,但都没有成功。我什至不知道我是否该关闭或离开该怎么做。
接口仅提供有关特定类can的实现方案的蓝图。为了给您一个具体的例子,请考虑接口Fruit
。
public interface Fruit {
void eat();
}
现在,实例化接口没有意义,因为它只是一个抽象。但是,实际上创建类Banana
或Apple
的对象将是有意义的。而且由于这些都是水果,所以可以吃。
for (Fruit f : fruits) {
f.eat();
}
由于您的Vehicle
类实现了Nitrous
,所以它的所有子类也可以分配给该特定类型,并且它们履行其合同,即nos()
。
Ford mustang = new Ford("Mustang", 135, 125);
Nitrous asNitrous = mustang; // works
mustang.nos(); // works
相关:What is the definition of an interface in object oriented programming?