Fork me on GitHub

小型通讯录

定义Friend类,编写它具有的属性:姓名(name)、电话(phone)、邮箱(email)和公司(comp)以及它的方法showInfo()。编写测试类AddFriend,实现添加联系人的功能(从键盘输入)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//AddFriend.java
import 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();
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//Friend.java
public 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!