java类private/this的使用
package 类的练习; public class Person { private String name; private int age; private String sex; private String hobby; public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getHobby() { return hobby; } public void setHobby(String hobby) { this.hobby = hobby; } public void showInfo() { System.out.println(this.name+"----"+this.age); } //name :方法的参数name //this.name:当前类的属性name public void setName(String name) { this.name=name; } public String getName() { return name; } public void setAge(int age) { if(age<0) { System.out.println("我滴个乖乖,年龄能成负的?"); this.age=-1; System.out.println("年龄有误!"); } else if(age>120) { System.out.println("人能活那么久?"); this.age=-1; System.out.println("年龄有误!"); }else { this.age=age; } } public int getAge() { return age; } } package 类的练习; public class TestPerson { public static void main(String[] args) { Person per=new Person(); per.setName("张三"); per.setAge(20); per.setSex("男"); per.setHobby("敲代码"); System.out.println("名字:"+per.getName()); System.out.println("年龄:"+per.getAge()); System.out.println("性别:"+per.getSex()); System.out.println("爱好:"+per.getHobby()); } }
道阻且长,行则将至

浙公网安备 33010602011771号