*create Date:2017-3-29
*modified Date:2017-3-29
*modified by:shark
*Description:對象練習
**/
public class MyPeople{
public String name;//公有屬性
public int age;//公有屬性
public void show(){//無返回公有方法
System.out.println("姓名:"+name);
System.out.println("年齡:"+age+"歲");
}
public int times(String old,String search){//返回值是int的公有方法
int weizhi=old.indexOf(search);
int sum=0;
while(weizhi!=-1){
sum++;
weizhi=old.indexOf(search,weizhi+search.length());
}
return sum;
}
public static void main(String[] args){//入口
MyPeople he=new MyPeople();
he.name="周柔輝";
he.age=26;
he.show();
System.out.println("'朋友'在'周柔輝是我朋友的朋友的朋友是好朋友朋友'出現的次數是:"+he.times("周柔輝是我朋友的朋友的朋友是好朋友朋友","朋友")+"次");
}
}
以上是部分公有私有的單純的類封裝的練習
之後是包含公有私有和接口的類的封裝
/**
*create Date:2017-3-29
*modified Date:2017-3-29
*modified by:shark
*Description:屬性修飾練習
**/
public class TeacherDemo{
public static void main(String [] args){
Teache teache=new Teache();
teache.setname("周柔輝");
teache.setage(20);
System.out.println(teache.show());
}
}
class Teache{//類
private String name;//私有屬性
private int age;//私有屬性
private int block=0;//私有屬性判斷年齡是否合格
private String teache;//私有屬性
public void setname(String name){//公有方法爲私有屬性賦值
this.name=name;
}
public void setage(int age){//共有方法判斷屬性是否合格合格爲私有屬性賦值
if(age<23){
System.out.println("年齡太小了");
this.block=1;
}else{
this.age=age;
}
}
private void beteache(){//私有方法得到是否可以成爲老師的字符串
if(this.block==0){
this.teache="老師姓名:"+this.name+"\n老師年齡:"+this.age+"歲";
}else{
this.teache="年齡不合格不能當老師";
}
}
public String show(){//外部調用接口
this.beteache();//調用私有方法
return this.teache;
}
}
帶構造函數的類:
/**
*create Date:2017-3-29
*modified Date:2017-3-29
*modified by:shark
*Description:屬性修飾練習
**/
public class TeacherDemo{
public static void main(String [] args){
Teache teache=new Teache("周柔輝",25);
/*teache.setname("周柔輝");
teache.setage(20);*/
System.out.println(teache.show());
}
}
class Teache{//類
private String name;//私有屬性
private int age;//私有屬性
private int block=0;//私有屬性判斷年齡是否合格
private String teache;//私有屬性
public Teache(String name,int age){
this.name=name;
if(age<23){
this.block=1;
}else{
this.age=age;
}
}
/*public void setname(String name){//公有方法爲私有屬性賦值
this.name=name;
}
*/
/*public void setage(int age){//共有方法判斷屬性是否合格合格爲私有屬性賦值
if(age<23){
System.out.println("年齡太小了");
this.block=1;
}else{
this.age=age;
}
}
*/
private void beteache(){//私有方法得到是否可以成爲老師的字符串
if(this.block==0){
this.teache="老師姓名:"+this.name+"\n老師年齡:"+this.age+"歲";
}else{
this.teache="年齡不合格不能當老師";
}
}
public String show(){//外部調用接口
this.beteache();//調用私有方法
return this.teache;
}
}