In: Computer Science
Add more methods to SmartPhone.
Given Files:
public class Phone { protected String name; protected long number; public Phone() { this("None", -1); } public Phone(String name) { this(name, -1); } public Phone(String name, long number) { this.name = name; this.number = number; } public String getName() { return name; } public long getNumber() { return number; } }
And:
public class Demo3 { public static void test(SmartPhone f) { System.out.print(f); if (f.hasPhoneNumber()) { System.out.println("Area code: " + f.getAreaCode()); System.out.println("Prefix: " + f.getPrefix()); System.out.println("Line number: " + f.getLineNumber()); } System.out.println(); } public static void main(String[] args) { SmartPhone test1 = new SmartPhone("Bret", "1234567890"); SmartPhone test2 = new SmartPhone("Alice", "8059226966", "[email protected]"); SmartPhone test3 = new SmartPhone(); test(test1); test(test2); test(test3); } }
And:
public class SmartPhone extends Phone { private String email; private String phone; private String phone2; public SmartPhone() { super("None",-1); phone = "Not set"; email = "None"; phone2 = "Not set"; } public SmartPhone(String name, String phone) { super(name, Long.parseLong(phone)); this.phone = phone; this.email = "None"; } public SmartPhone(String name, String phone, String email) { super(name, Long.parseLong(phone)); this.email = email; this.phone = phone; } public String toString() { return "Name: " + name + "\n" + "Phone: " + phone + "\n" + "Email: " + email + "\n"; } }
////////////////////////////////////////// Output //////////////////////////////////////////
Name: Bret\n Phone: 1234567890\n Email: None\n Area code: 123\n Prefix: 456\n Line number: 7890\n \n Name: Alice\n Phone: 8059226966\n Email: [email protected]\n Area code: 805\n Prefix: 922\n Line number: 6966\n \n Name: None\n Phone: Not set\n Email: None\n \n
public class SmartPhone extends Phone { private String email; private String phone; private String phone2; public SmartPhone() { super("None",-1); phone = "Not set"; email = "None"; phone2 = "Not set"; } public SmartPhone(String name, String phone) { super(name, Long.parseLong(phone)); this.phone = phone; this.email = "None"; } public SmartPhone(String name, String phone, String email) { super(name, Long.parseLong(phone)); this.email = email; this.phone = phone; } public String toString() { return "Name: " + name + "\n" + "Phone: " + phone + "\n" + "Email: " + email + "\n"; } public boolean hasPhoneNumber() { return !phone.equals("Not set"); } public String getAreaCode() { return phone.substring(0, 3); } public String getPrefix() { return phone.substring(3, 6); } public String getLineNumber() { return phone.substring(6); } }