定义一个Computer类,有属性private int state 表示为状态码,有2个方法,一个是run()方法,当state 为1时,在方法里正常显示“电脑成功运行”,当state 为2时,在方法里抛出自定义异常MaoYanException,显示"电脑冒烟了"。
时间: 2024-03-27 20:36:15 浏览: 17
好的,这里是您需要的代码:
```java
class MaoYanException extends Exception {
public MaoYanException(String message) {
super(message);
}
}
class Computer {
private int state;
public Computer(int state) {
this.state = state;
}
public void run() throws MaoYanException {
if (state == 1) {
System.out.println("电脑成功运行");
} else if (state == 2) {
throw new MaoYanException("电脑冒烟了");
}
}
}
```
在这里,我们定义了一个名为`Computer`的类,它有一个名为`state`的私有属性,表示电脑的状态码。然后,我们定义了一个名为`run()`的方法,根据`state`的值,它可以正常运行或抛出一个自定义异常`MaoYanException`。如果`state`为1,则会正常显示“电脑成功运行”,如果`state`为2,则会抛出异常并显示“电脑冒烟了”。
相关问题
(1)定义一个接口Compute含有一个方法int computer(int n, int m)
Sure! 这里是定义一个名为Compute的接口,包含一个名为computer的方法,该方法接受两个整数作为参数并返回一个整数。以下是该接口的代码示例:
```java
public interface Compute{
int computer(int n, int m);
}
```
希望这能解决您的问题!如果您有任何其他问题,请继续问我。
定义一个person类,自定义属性和方法,定义一个student类继承person类
下面是一个示例代码,定义了一个`Person`类和一个`Student`类,`Student`类继承自`Person`类,并且添加了一个`study`方法。
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Student(Person):
def __init__(self, name, age, major):
super().__init__(name, age)
self.major = major
def study(self):
print(f"{self.name} is studying {self.major}")
```
在上面的代码中,`Person`类有两个属性:`name`和`age`,并且有一个构造函数`__init__`来初始化这些属性。`Student`类继承了`Person`类,并且添加了一个新的属性`major`,以及一个新的方法`study`。`study`方法输出学生的姓名和专业。
下面是一个使用示例:
```python
person1 = Person("John", 30)
print(person1.name) # "John"
print(person1.age) # 30
student1 = Student("Mary", 20, "Computer Science")
print(student1.name) # "Mary"
print(student1.age) # 20
print(student1.major) # "Computer Science"
student1.study() # "Mary is studying Computer Science"
```
在上面的示例中,我们创建了一个`Person`对象和一个`Student`对象,分别通过`name`和`age`属性来初始化。对于`Student`对象,我们还需要传递一个`major`参数来初始化。我们还调用了`study`方法,这个方法输出了学生的姓名和专业。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)