// 构造器(constructor)。
public class test10 {
public static void main(String[] args) {
// 确定构造器的参数。
FC fc = new FC(20, "Starty",3.4);
// 调用行为。
fc.show();
}
}
// 构造器的作用:对对象进行初始化
class FC{
// 属性
int age ;
String name;
double money;
// 构造器:
//构造器没有返回值
// 构造器的名字必须和类的名字相同。
// 在使用类的时候,会自动调用构造器。
public FC(int age,String name,double money){
// 开始初始化
// 其中的this是指向这个类。
this.age = age;
this.name = name;
this.money = money;
}
// 在一个类中可以定义多个构造器(构造器重载)。
public FC(int age,double money)
{
this.age = -1;
this.name = "start";
this.money = 3.1415926;
}
// 如果程序员没有创建一个构造器,编译器会自动创建一个构造器,如下:
// public FC()
// {
// }
// 定义一个显示的默认构造器(如果一个类中有其他的构造器,如果还需要默认的构造器,需要定义)
public FC(){};
// 行为
void show()
{
System.out.println(this.age);
System.out.println(this.name);
System.out.println(this.money);
}
}
Java 构造器(构造函数)
最新推荐文章于 2023-02-16 14:30:22 发布