Java创建一个学生类,使用方法重载,创建speak方法
时间: 2024-05-27 07:12:00 浏览: 18
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public void speak() {
System.out.println("我叫" + name + ",今年" + age + "岁。");
}
public void speak(String message) {
System.out.println("我叫" + name + ",今年" + age + "岁," + message);
}
}
// 使用方法重载创建speak方法
// 可以根据需要传入不同的参数来输出不同的信息
// 如果不传入参数,则输出默认的信息
相关问题
用方法重载创建一个student类
好的,以下是用方法重载创建一个student类的代码示例:
```java
public class Student {
private String name;
private int age;
private String gender;
public Student(String name) {
this.name = name;
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public Student(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
// getters and setters
}
```
这个student类有三个构造方法,分别接受不同数量和类型的参数,可以根据需要选择使用哪个构造方法来创建对象。
创建一个javascript类,模拟实现方法的重载
可以使用ES6的语法来实现方法的重载,具体代码如下:
class MyClass {
constructor() {
this.overloadedMethods = {};
}
addMethod(name, fn) {
if (this.overloadedMethods[name]) {
this.overloadedMethods[name].push(fn);
} else {
this.overloadedMethods[name] = [fn];
}
}
callMethod(name, ...args) {
const methods = this.overloadedMethods[name];
if (!methods) {
throw new Error(`Method ${name} not found`);
}
for (let i = 0; i < methods.length; i++) {
const method = methods[i];
if (method.length === args.length) {
return method(...args);
}
}
throw new Error(`No matching method found for ${name}`);
}
}
使用示例:
const myClass = new MyClass();
myClass.addMethod('foo', function() {
console.log('foo with no arguments');
});
myClass.addMethod('foo', function(a) {
console.log(`foo with argument ${a}`);
});
myClass.addMethod('foo', function(a, b) {
console.log(`foo with arguments ${a} and ${b}`);
});
myClass.callMethod('foo'); // logs "foo with no arguments"
myClass.callMethod('foo', 1); // logs "foo with argument 1"
myClass.callMethod('foo', 1, 2); // logs "foo with arguments 1 and 2"
相关推荐
![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)