在java中(1) Student 类中包含姓名、成绩两个属性。 (2)分别给这两个属性定义两个方法,个方法用于设置值,另一个方法用于 获取值。(3)Student类中定义一个无参的构造方法和一个接收两个参数的构造方法,两个参数分别为姓名和成绩属性赋值。 (4)在测试类中创建两个Student对象,一个使用无参的构造方法,然后调用方法给姓名和成绩赋值,另一个使用有参的构造方法,在构造方法中给姓名和成绩赋值。
时间: 2024-02-11 07:03:38 浏览: 27
好的,这是一个关于Java的面向对象编程问题,我来回答一下。
1. 首先定义一个Student类,包含姓名、成绩两个属性,分别定义两个方法用于设置值和获取值:
```java
public class Student {
private String name;
private int score;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
```
2. 在Student类中定义一个无参的构造方法和一个接收两个参数的构造方法,两个参数分别为姓名和成绩属性赋值:
```java
public class Student {
private String name;
private int score;
public Student() {
this.name = "";
this.score = 0;
}
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
```
3. 在测试类中创建两个Student对象,一个使用无参的构造方法,然后调用方法给姓名和成绩赋值,另一个使用有参的构造方法,在构造方法中给姓名和成绩赋值:
```java
public class Test {
public static void main(String[] args) {
// 创建无参对象
Student stu1 = new Student();
stu1.setName("Tom");
stu1.setScore(90);
System.out.println("姓名:" + stu1.getName() + ",成绩:" + stu1.getScore());
// 创建有参对象
Student stu2 = new Student("Jerry", 80);
System.out.println("姓名:" + stu2.getName() + ",成绩:" + stu2.getScore());
}
}
```
输出结果:
```
姓名:Tom,成绩:90
姓名:Jerry,成绩:80
```
希望我的回答能够帮助到你!
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)