我已閱讀了關於超類,抽象等。我理解了大部分的一般想法。 我現在有3類(主,超類,子類)從java中的超類返回數據
第一類:抓取用戶類型的汽車的用戶里程和加侖,發送數據到子類。子類將數據設置爲變量。
我想找出一種方法來打印每加侖汽車的里程數。這種計算方法在超類內,但我找不到打印方法的方法。 這裏是我的代碼:
主要
import java.util.Scanner;
public class StartingPoint {
public static void main (String[]args)
{
Scanner input = new Scanner(System.in); //Get user input
Mercedes mCar = new Mercedes(); //Accesses subclass of the Car superclass (Mercedes)
Toyota tCar = new Toyota(); //Accesses subclass of the Car superclass (Toyota)
System.out.println("Do you own a mercedes or a toyota?"); //Get car type
String carName = input.nextLine();
if (carName.charAt(0) == 'm' || carName.charAt(0) == 'M')
{
System.out.println("How many miles have you travelled?");
double miles = input.nextDouble();
System.out.println("How many gallons have you used?");
double gallons = input.nextDouble();
mCar.setGallons(gallons);
mCar.setMiles(miles);
}
else if (carName.charAt(0) == 't' || carName.charAt(0) == 'T')
{
//NOT CODED YET
}
else
{
System.out.println("Not a valid car name for the system...");
}
}
}
超級類
public abstract class Car {
public double calcMPG(double miles, double gallons)
{
return (miles/gallons);
}
}
超類(汽車)的子類
public class Mercedes extends Car {
private double miles;
private double gallons;
public Mercedes()
{
miles = 0;
gallons = 0;
}
public void setMiles(double inputMiles)
{
miles = inputMiles;
}
public void setGallons(double inputGallons)
{
gallons = inputGallons;
}
}
我將此行添加到我的主類,不知道是否是最好的方式去做這件事。的System.out.println(Mercedes.calcMPG(英里,加侖)); – KnowledgeGeek
我也想到我可以添加一個方法(計算)到梅賽德斯班,並呼籲super.calcMPG(英里,加侖),並有該方法打印.. System.out.println(super.calcMPG(英里,加侖)和然後調用mCar.calc();它會打印 – KnowledgeGeek