0
点赞
收藏
分享

微信扫一扫

31_Person类和测试类的实现

cnlinkchina 2022-01-05 阅读 40

案例题目

  • 编程实现People类的封装,特征有:姓名、年龄、国籍,要求提供打印所有特征的方法。

  • 编程实现PeopleTest类,main 方法中使用有参方式构造两个对象并打印。

    /*
    	编程实现People类的封装
     */
     public class People {
    	 
    	 // 1、私有化成员变量
    	 private String name; // 姓名
    	 private int age; // 年龄
    	 private String country; // 国籍
    	 
    	 // 3、在构造方法中调用set方法进行合理值的判断
    	 public People() {}
    	 public People(String name, int age, String country) {
    		 setName(name);
    		 setAge(age);
    		 setCountry(country);
    	 }
    	 
    	 // 2、提供公有的get和set方法,并在方法体中进行合理值的判断
    	 public String getName() {
    		 return name;
    	 }
    	 
    	 public int getAge() {
    		 return age;
    	 }
    	 
    	 public String getCountry() {
    		 return country;
    	 }
    	 
    	 public void setName(String name) {
    		 this.name = name;
    	 }
    	 
    	 public void setAge(int age) {
    		 if(age > 0 && age <= 150) {
    			 this.age = age;
    		 } else {
    			 System.out.println("年龄不合理!!!");
    		 }
    	 }
    	 
    	 public void setCountry(String country) {
    		 this.country = country;
    	 }
    	 
    	 public void show() {
    		 System.out.println("我是" + getName() + ",今年" + getAge() + "岁了,来自" + getCountry() + "\n");
    	 }
     }
    
    
    
    /*
    	编程实现People类的测试
     */
     public class PeopleTest {
    	 
    	 public static void main(String[] args) {
    		 
    		 // 1、使用有参方式构造两个People类型的对象并打印特征
    		 People p1 = new People("淳神", 21, "中国");
    		 p1.show(); // 我是淳神,今年21岁了,来自中国
    		 
    		 People p2 = new People("佘儿", 20, "中国");
    		 p2.show(); // 我是佘儿,今年20岁了,来自中国
    	 }
     }
    
  • 在这里插入图片描述

举报

相关推荐

0 条评论