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

}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值