我只是在学习阶段&我在这里使用一些多态技术。这是代码:
package com.company;
class Car{
private String name;
private int cylinder;
private boolean engine;
private int wheels;
public Car(String name, int cylinder) {
this.name = name;
this.cylinder = cylinder;
this.engine = true;
this.wheels = 4;
}
public String startEngine(int fuel){
if(fuel>0){
return "Start button pressed";
} else{
return "First fill some fuel";
}
}
public String accelerate(int speed){
return "Car is accelerated with speed " + speed;
}
public String brake(int speed){
return "Brake is presses. Now speed is " + speed;
}
public String getName() {
return name;
}
public int getCylinder() {
return cylinder;
}
}
class Fortuner extends Car{
public Fortuner() {
super("Fortuner", 4);
}
@Override
public String accelerate(int speed) {
return "Fortuner is accelerated with speed " +speed;
}
@Override
public String brake(int speed) {
return "Now your Fortuner is moving with " + speed + " kph";
}
}
class Hondacity extends Car{
public Hondacity() {
super("Hinda City", 6);
}
@Override
public String accelerate(int speed) {
return "Honda City is accelerated with speed " +speed;
}
@Override
public String brake(int speed) {
return "Now your Honda City is moving with " + speed + " kph";
}
}
class Omni extends Car{
public Omni() {
super("Omni", 1);
}
@Override
public String accelerate(int speed) {
return "Omni is accelerated with speed " +speed;
}
@Override
public String brake(int speed) {
return "Now your Omni is moving with " + speed + " kph";
}
}
public class Main {
public static void main(String[] args) {
for(int j=0; j<3; j++){
Car car = speedup();
System.out.println(car.accelerate(50));
}
}
public static Car speedup() {
for(int i=0; i<3; i++){
switch(i){
case 0: return new Fortuner();
case 1: return new Hondacity();
case 2: return new Omni();
}
}
return null;
}
}
当我运行它时,它会提供如下输出:
Fortuner以50的速度加速Fortuner加速 速度50 Fortuner速度加快50
但我想提供类似这样的输出
Fortuner以50的速度加速 速度50 Omni以速度加速50
我知道每次方法运行时都会发生这种情况。我该如何解决?请告诉我糟糕的算法,因为我只是一个学习者。
答案 0 :(得分:1)
你的方法O(m+n)
总是返回一个Fortuner,因为它永远不会得到任何进一步的结果。 IntersectWith
命令始终退出循环。所以,如果你想获得所有课程,你必须这样做:
speedup()
答案 1 :(得分:0)
在你的方法speedup()中,每次j的值都是0.所以它总是返回Fortuner。我已经删除了这个方法来解决它。
public int a;
public string b;