小型通讯录 发表于 2017-09-23 | | 阅读次数: 定义Friend类,编写它具有的属性:姓名(name)、电话(phone)、邮箱(email)和公司(comp)以及它的方法showInfo()。编写测试类AddFriend,实现添加联系人的功能(从键盘输入)1234567891011121314151617181920212223242526272829303132//AddFriend.javaimport java.util.Scanner;public class AddFried { public static void main(String[] args) { // TODO Auto-generated method stub Friend friend= new Friend(); Scanner inputScanner= new Scanner(System.in); System.out.println("请输入联系人姓名: "); friend.setName(inputScanner.next()); System.out.println("请输入联系人电话: "); friend.setPhone(inputScanner.next()); System.out.println("请输入联系人电子邮箱: "); friend.setEmail(inputScanner.next()); System.out.println("请输入联系人公司: "); friend.setComp(inputScanner.next()); friend.showInfo(); // friend.name= "花千骨";// friend.showInfo(); /* * 没有封装,将String name等四个变量封装为private就行 * 封装:把不想或不该告诉别人的事情隐藏起来 * 具体做法:将属性私有化,提供公有化的方法来访问属性 * */ inputScanner.close(); }} 12345678910111213141516171819202122232425262728293031323334353637383940//Friend.javapublic class Friend { String name;// 默认private String phone; String email; String comp; public void setName(String name) { this.name= name;// 访问本类中的属性和方法 } public String getName(){ return name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getComp() { return comp; } public void setComp(String comp) { this.comp = comp; } public void showInfo(){ System.out.println("新朋友的联系信息为: "); System.out.println("姓名: "+ this.getName()); System.out.println("电话: "+ this.getPhone()); System.out.println("电子邮箱: "+ this.getEmail()); System.out.println("公司: "+ this.hashCode()); }} Your support will encourage me to continue to create! Donate WeChat Pay Alipay