面试题答案
一键面试在Java中,一个类可以有多个构造函数。这叫构造函数重载机制。
以下是通过不同构造函数来实例化包含姓名和年龄属性的Person
类的示例代码:
public class Person {
private String name;
private int age;
// 第一个构造函数,接收姓名和年龄
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// 第二个构造函数,只接收姓名,年龄默认为0
public Person(String name) {
this.name = name;
this.age = 0;
}
// 获取姓名的方法
public String getName() {
return name;
}
// 获取年龄的方法
public int getAge() {
return age;
}
}
可以通过以下方式使用这些构造函数:
public class Main {
public static void main(String[] args) {
// 使用第一个构造函数实例化对象
Person person1 = new Person("Alice", 25);
System.out.println("姓名:" + person1.getName() + ",年龄:" + person1.getAge());
// 使用第二个构造函数实例化对象
Person person2 = new Person("Bob");
System.out.println("姓名:" + person2.getName() + ",年龄:" + person2.getAge());
}
}