gpt4 book ai didi

java - 如何编写返回抽象类实例的方法?

转载 作者:行者123 更新时间:2023-11-29 03:36:09 25 4
gpt4 key购买 nike

我是 Java 的初学者,我试图理解抽象类。下面是我写的代码;问题是:我如何编写一个方法来返回该类的一个实例。

public abstract class VehicleEngine
{
protected String name;
protected double fabricationCons;
protected double consum;
protected int mileage;

public VehicleEngine(String n, double fC)
{
name = n;
fabricationCons = fC;
mileage = 0;
consum = 0;
}

private void setFabricationCons(double fC)
{
fabricationCons = fC;
}

public abstract double currentConsum();

public String toString()
{
return name + " : " + fabricationCons + " : " + currentConsum();
}

public void addMileage(int km)
{
mileage += km;
}

public double getFabricationConsum()
{
return fabricationCons;
}

public String getName()
{
return name;
}

public int getMileage()
{
return mileage;
}

//public VehicleEngine get(String name){
//if(getName().equals(name)){
//return VehicleEngine;
//}
//return null;
//}
}

public class BenzinVehicle extends VehicleEngine
{
public BenzinVehicle(String n, double fC)
{
super(n, fC);
}

@Override
public double currentConsum()
{
if (getMileage() >= 75000) {
consum = getFabricationConsum() + 0.4;
} else {
consum = getFabricationConsum();
}
return consum;
}
}

public class DieselVehicle extends VehicleEngine
{
public DieselVehicle(String n, double fC)
{
super(n, fC);
}

@Override
public double currentConsum()
{
int cons = 0;
if (getMileage() < 5000) {
consum = getFabricationConsum();
} else {
consum = getFabricationConsum() + (getFabricationConsum() * (0.01 * (getMileage() / 5000)));
}
return consum;
}
}

这是主要的。

public class Subject2
{
public static void main(String[] args)
{
VehicleEngine c1 = new BenzinVehicle("Ford Focus 1.9", 5.0);
DieselVehicle c2 = new DieselVehicle("Toyota Yaris 1.4D", 4.0);
BenzinVehicle c3 = new BenzinVehicle("Citroen C3 1.6",5.2);

c1.addMileage(30000);
c1.addMileage(55700);
c2.addMileage(49500);
c3.addMileage(35400);

System.out.println(c1);
System.out.println(c2);
System.out.println(VehicleEngine.get("Citroen C3 1.6")); //this is the line with problems
System.out.println(VehicleEngine.get("Ford Focus "));
}
}

输出应该是:

Ford Focus 1.9 : 5.0 : 5.4
Toyota Yaris 1.4D : 4.0 : 4.36
Citroen C3 1.6 : 5.2 : 5.2
null

最佳答案

根据定义,您可以返回抽象类的实例。您可以做的是返回扩展它的具体(非抽象)子类之一的实例。例如,在 VehicleEngine 中,您可以创建一个返回给定实例类型和预期参数的实例的工厂,但这些实例必须是 VehicleEngine 的具体子类>

关于java - 如何编写返回抽象类实例的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15441277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com