java--面向对象之封装(有参构造和无参构造)

不念不忘少年蓝@ 2022-06-04 09:56 355阅读 0赞

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();
}
}

发表评论

表情:
评论列表 (有 0 条评论,355人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java构造函数

    一 点睛 1 如果一个类没有定义任何构造函数,那么该类会自动生成1个默认的构造函数。默认构造函数没有参数。 2 如果一个类定义了构造函数,但这些构造函数都有参数,那么不会生