-
构造器方法重载练习
-
(1)定义Person类,有4个属性:String name; int age; String school; String major,
-
(2)定义Person类的3个构造方法:
-
第一个构造方法Person(String n, int a)设置类的name和age属性;
-
第二个构造方法Person(String n, int a, String s)设置类的name,
-
age 和school属性;
-
第三个构造方法Person(String n, int a, String s, String m)设置类的name, age ,school和major属性;
-
(3)在main方法中分别调用不同的构造方法创建的对象,并输出其属性值。
-
/*
-
* 构造器方法重载练习
-
* (1)定义Person类,有4个属性:String name; int age; String school; String major,
-
(2)定义Person类的3个构造方法:
-
第一个构造方法Person(String n, int a)设置类的name和age属性;
-
第二个构造方法Person(String n, int a, String s)设置类的name,
-
age 和school属性;
-
第三个构造方法Person(String n, int a, String s, String m)设置类的name, age ,school和major属性;
-
(3)在main方法中分别调用不同的构造方法创建的对象,并输出其属性值。
-
-
*/
-
package com.troubleshooting.javase.ex;
-
-
public class Person {
-
// 定义Person类,有4个属性:String name; int age; String school; String major,
-
private String name;
-
private int age;
-
private String school;
-
private String major;
-
-
public String getName() {
-
return name;
-
}
-
-
public void setName(String name) {
-
this.name = name;
-
}
-
-
public int getAge() {
-
return age;
-
}
-
-
public void setAge(int age) {
-
this.age = age;
-
}
-
-
// 第一个构造方法Person(String n, int a)设置类的name和age属性;
-
public Person(String n, int a) {
-
name = n;
-
age = a;
-
}
-
-
// 第二个构造方法Person(String n, int a, String s)设置类的name,age 和school属性;
-
public Person(String n, int a, String s) {
-
name = n;
-
age = a;
-
school = s;
-
}
-
-
// 第三个构造方法Person(String n, int a, String s, String m)设置类的name, age
-
// ,school和major属性;
-
public Person(String n, int a, String s, String m) {
-
name = n;
-
age = a;
-
school = s;
-
major = m;
-
}
-
-
public String getInfo() {
-
return "name:\t" + name + "\tage:\t" + age + "\tschool:\t" + school + "\tmajor:\t" + major;
-
}
-
}
-
-
package com.troubleshooting.javase.ex;
-
-
public class TestPerson {
-
public static void main(String[] args) {
-
Person p1 = new Person("Jerry", 22);
-
Person p2 = new Person("Jerry", 22, "TsingHua");
-
Person p3 = new Person("Jerry", 22, "TsingHua", "Java");
-
System.out.println(p1.getInfo());
-
System.out.println(p2.getInfo());
-
System.out.println(p3.getInfo());
-
}
-
}
显示结果:
name: Jerry age: 22 school: null major: null
name: Jerry age: 22 school: TsingHua major: null
name: Jerry age: 22 school: TsingHua major: Java
阅读(3321) | 评论(0) | 转发(0) |