java封装类练习

/**
*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;
}

}

你可能感兴趣的:(java)