1、创建一个students类
public class students{ //students类的属性 private String name; private int age; private String gender; //students类的方法 public students(){ //默认方法 } public students(String name,int age,String gender){ //students类的构造方法 this.name = name ; this.age = age ; this.gender = gender ; } //students的get方法获取属性值 public String getName(){ return this.name; } public int getAge(){ return this.age; } public String getGender(){ return this.gender; } //students的set方法对属性进行赋值 public void setName(String name){ this.name = name ; } public void setAge(int age){ //对age进行范围圈定和判断 if(age>45 || age<15){ this.age=18; }else{ this.age = age ; } } public void setGender(String gender){ this.gender = gender ; } }
2、创建一个studentsDemo测试类
public class studentsDemo { public static void main(String[] args) { //实例化对象 students st = new students() ; // st.name="小明"; // st.age=12; // st.gender="男"; // System.out.println(st.name+"\n"+st.age+"\n"+st.gender+"\n"); st.setName("小虎"); st.setAge(14); st.setGender("男"); System.out.println(st.getName()+"\n"+st.getAge()+"\n"+st.getGender()+"\n"); } }
输出结果:
小虎
18
男
本文出自 “技术进阶” 博客,请务必保留此出处http://vipnoon.blog.51cto.com/7589908/1792786
原文地址:http://vipnoon.blog.51cto.com/7589908/1792786