我是新来的继承和抽象类。如何用抽象类输出
在这个例子中,我正在设计一个电话簿,可以有一个人或一个企业。该人拥有头衔,名字,姓氏和电话号码。该企业有一个企业名称和一个电话号码。 我创建了抽象方法GetName 一个抽象类(这听起来确实简单了你们,但请多多包涵!)
public abstract class PhoneBook {
private String phone;
public boolean setPhone(String p) //final
{
boolean flag = false;
if(p.length()!= 10)
{
flag = false;
}
for (int i = 0; i < p.length(); i++)
{
if(Character.isDigit(p.charAt(i)))
{
phone = p;
flag = true;
}
}
return flag;
}
public abstract String getName();
}
我的两个子类是个人和企业。该人的getName方法连接标题,f名称,l名称。 在主要我创建了一个电话簿数组(抽象数组),可以同时拥有一个人或一个企业。
我在与输出困难......我怎么访问getPhone(在抽象类)来输出呢?
这是最主要的(我目前只工作的人的部分)
import javax.swing.*;
公共类PhoneBookEntries {
public static final int MAX = 100;
public static void main(String[] args) {
PhoneBook[] phone = new PhoneBook[100];
int selection;
int i = 0;
do{
selection = Integer.parseInt(JOptionPane.showInputDialog("Would you like to add a\n1.person\n2.business\nto the phone book?"));
switch(selection)
{
case 1: phone[i]= fillPerson();
break;
case 2: fillBusiness();
break;
}
}while(i < MAX && JOptionPane.showConfirmDialog(null, "Add another entry to phone book?")==JOptionPane.YES_OPTION);
//output
String output;
output = phone[i].getName();
JOptionPane.showMessageDialog(null, output);
}
private static PhoneBook fillPerson()
{
Person someone = new Person();
someone.setTitle(JOptionPane.showInputDialog("Enter your title\n(Mr., Mrs., Ms., or Dr.)"));
someone.setFName(JOptionPane.showInputDialog("Enter the first name of the person: "));
someone.setLName(JOptionPane.showInputDialog("Enter the last name of the person: "));
while(!someone.setPhone(JOptionPane.showInputDialog("Enter your 10 digit phone number: ")))
JOptionPane.showMessageDialog(null, "Error. Please enter only 10 numerical values\n(examle: 7034567890");
return someone;
}
private static void fillBusiness()
{
}
}
的getName我可以,因为我很容易地访问有PhoneBook []。我在想我需要一个toString在一起(所有的名字和电话号码),但在主要我不能访问该toString,因为我没有一个人实例化? 很抱歉,如果这是混乱...我只是打字思想的我(差)的火车......
为什么你不能在抽象类中做'this.getPhone()'?只需在那里定义方法和属性,因为两个实现都具有该属性... – hvgotcodes 2012-04-24 20:34:55
fwiw,您可能想要更改抽象类名称。它不代表电话簿;它代表一个条目.... – hvgotcodes 2012-04-24 20:35:36