用java定义一个学生类Student,属性有姓名(name)、年龄(age)。行为有:学习(study)、睡觉(sleep)。在测试类Demo_Student.中实例化一个学生对象Wang.并调用学习(study)、睡觉(sleep)
时间: 2023-05-15 16:06:43 浏览: 110
好的,以下是Java定义学生类Student的代码:
```
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public void study() {
System.out.println(name + "正在学习");
}
public void sleep() {
System.out.println(name + "正在睡觉");
}
}
```
以下是测试类Demo_Student的代码:
```
public class Demo_Student {
public static void main(String[] args) {
Student Wang = new Student("Wang", 18);
Wang.study();
Wang.sleep();
}
}
```
输出结果为:
```
Wang正在学习
Wang正在睡觉
```
相关问题
C++定义一个学生类Student,属性有学号(number)、姓名(name)、年龄(age),行为是学习(Study),在主函数中定义学生类对象,为该对象所拥有的属性赋值,并输出该对象的所有信息。
以下是C++定义一个学生类Student的示例代码:
```cpp
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
// 构造函数
Student(string number, string name, int age) {
this->number = number;
this->name = name;
this->age = age;
}
// 行为:学习
void Study() {
cout << name << " is studying." << endl;
}
// 输出学生信息
void PrintInfo() {
cout << "Number: " << number << endl;
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
private:
string number; // 学号
string name; // 姓名
int age; // 年龄
};
int main() {
// 创建学生对象并初始化属性
Student stu("1001", "Tom", 18);
// 输出学生信息
stu.PrintInfo();
// 学生进行学习
stu.Study();
return 0;
}
```
运行结果:
```
Number: 1001
Name: Tom
Age: 18
Tom is studying.
```
、定义一个学生类Student,属性有学号(number)、姓名(name)、年龄(age),行为是学习(Study),在主函数中定义学生类对象,为该对象所拥有的属性赋值,并输出该对象的所有信息。
好的,以下是实现这个要求的 Python 代码:
```python
class Student:
def __init__(self, number, name, age):
self.number = number
self.name = name
self.age = age
def Study(self):
print(f"{self.name}正在学习")
# 创建学生类对象
s = Student("001", "Tom", 18)
# 为对象属性赋值
s.number = "002"
s.name = "Jack"
s.age = 17
# 输出对象信息
print(f"学号:{s.number}")
print(f"姓名:{s.name}")
print(f"年龄:{s.age}")
s.Study()
```
输出结果如下:
```
学号:002
姓名:Jack
年龄:17
Jack正在学习
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)