java類private/this的使用
阿新 • • 發佈:2020-11-21
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; } publicvoid 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()); } }