我有一个PersonalContact类和一个BusinessContact类设置,并且我想使用此驱动程序来提示用户输入联系信息。输入信息后,我想使用这些类来打印其toStrings以显示联系信息。我认为我需要创建一个新的PersonalContact或BusinessContact对象,对吗?该基类称为Contact,它是一个抽象类。
import java.util.Scanner;
public class PlannerMain {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
while (true) {
System.out.println("Create new contact?");
System.out.println("1.Personal contact ");
System.out.println("2.Business Contact ");
System.out.println("3.Exit.");
int option = scanner.nextInt();
if (option == 1) { //Create Personal Contact
System.out.println("Name?");
String name = scanner.next();
System.out.println("Age?");
int age = scanner.nextInt();
System.out.println("Address?");
String address = scanner.next();
System.out.println("City?");
String city = scanner.next();
System.out.println("State?");
String state = scanner.next();
System.out.println("Zip");
String zip = scanner.next();
PersonalContact pc = new PersonalContact;
} // End option 1
else if (option == 2) { // Create Business Contact
System.out.println("Name?");
String name = scanner.next();
System.out.println("Age?");
int age = scanner.nextInt();
System.out.println("Business Phone?");
String businessPhone = scanner.next();
System.out.println("Cellphone?");
String cellPhone = scanner.next();
BusinessContact bc = new BusinessContact;
} // End option 2
else if (option == 3) { /** Terminates the program */
System.exit(0);
} // End option 3
} // End while
}// End void main
}// End
最佳答案
如果您的人员类别是这样的:
public abstract class Contact{
String name;
int age;
public Contact(String name, int age){
this.name = name;
this.age = age;
}
}
那么您的BusinessContact可能看起来像这样
public class BusinessContact extends Contact {
String businessPhone;
String cellPhone;
public BusinessContact(String name, int age, String businessPhone, String cellPhone){
super(name, age);
this.businessPhone = businessPhone;
this.cellPhone = cellPhone;
}
public String toString(){
return "Name: " + this.name + " Age: " + Integer.toString(age) + " Business Phone: " + businessPhone + " Cell Phone: " + cellphone;
}
}
那么您可以替换以下行:
BusinessContact bc = new BusinessContact;
有了这个:
BusinessContact bc = new BusinessContact(name, age, businessPhone, cellPhone);
System.out.println(bc.toString());