java--面向对象之封装(有参构造和无参构造)
package test;
public class Person {
private String name;
private String sex;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Person(String name, String sex, int age) {
this.name = name;
this.sex = sex;
this.age = age;
}
public Person() {
}
public void display(){
System.out.println(“名字:”+this.name+” 性别:”+this.sex+” 年龄:”+this.age);
}
/*public String show(String name, String sex, int age){
return “名字:”+this.name+” 性别:”+this.sex+” 年龄:”+this.age;
}*/
}
Test:
package test;
import org.junit.Test;
public class jTest {
@Test
public void test1(){
//无参构造
Person p1=new Person();
Person p2=new Person();
Person p3=new Person();
p1.setName(“张三”);
p1.setSex(“男”);
p1.setAge(19);
p2.setName(“张”);
p2.setSex(“男”);
p2.setAge(19);
p3.setName(“三”);
p3.setSex(“男”);
p3.setAge(19);
//String totle=p1.show(“张三”,”男”,19);
System.out.println(“名字:”+p1.getName()+” 性别:”+p1.getSex()+” 年龄:”+p1.getAge());
System.out.println(“名字:”+p2.getName()+” 性别:”+p2.getSex()+” 年龄:”+p2.getAge());
System.out.println(“名字:”+p3.getName()+” 性别:”+p3.getSex()+” 年龄:”+p3.getAge());
//有参构造
Person person1=new Person(“张三”,”男”,19);
Person person2=new Person(“李四”,”女”,21);
Person person3=new Person(“王五”,”男”,18);
person1.display();
person2.display();
person3.display();
}
}
还没有评论,来说两句吧...