“你好,阿米戈!我接下来要讲解如何创建对象。”
“这有什么复杂的,里希叔叔?你只要编写一个新对象和类名称,指示正确的构造方法就行啦!”
“不错。但在这个过程中,对象内发生了什么?”
“发生什么?”
“是这样:对象创建分几个阶段完成。”
1) 首先,内存被分配给所有类的成员变量。
2) 然后初始化基类。
3) 所有变量被赋值(如果已指定值)。
4) 最后,调用构造方法。
“看起来并不难:首先是变量,然后是构造方法。”
“让我们看看这个包含两个类的例子,看看它的工作原理:”
| 代码 |
说明 |
class Pet
{
int x = 5, y = 5; ←-
int weight = 10; ←-
Pet(int x, int y)
{
this.x = x; ←-
this.y = y; ←-
}
}
class Cat extends Pet
{
int tailLength = 8; ←-
int age;
Cat(int x, int y, int age)
{
super(x, y); ←-
this.age = age; ←-
}
} |
声明两个类;Pet(pet) 和 Cat(cat)。 在 Cat 类中,我们看到对基类的构造方法的显式调用。 它应始终在构造方法的第一行。 分配内存后会发生以下情况: 18 – 调用基类的构造方法。 3, 4 – 初始化 Pet 中的变量。 8, 9 – 在 Pet 构造方法中执行代码。 然后 Cat 类开始初始化。 14 – 初始化 Cat 中的变量 19 – 在 Cat 构造方法中执行代码 |
public static void main(String[] args)
{
Cat cat = new Cat (50, 50, 5);
} |
|
“有点不明白。为什么要这么复杂?”
“如果你了解当前进程,就一点都不复杂:”
如果一个类没有任何构造方法,系统将自动创建。
| 默认构造方法 |
|
class Cat
{
int x = 5;
int y = 5;
} |
class Cat
{
int x = 5;
int y = 5;
public Cat()
{
}
} |
如果不调用基类的构造方法,它会被自动调用。
| 调用基类的构造方法 |
|
class Pet
{
public String name;
} |
class Pet extends Object
{
public String name;
public Pet()
{
super();
}
} |
class Cat extends Pet
{
int x = 5;
int y = 5;
} |
class Cat extends Pet
{
int x = 5;
int y = 5;
public Cat() { super(); }
} |
成员变量在构造方法中初始化。
| 初始化成员变量 |
|
class Cat
{
int x = 5; int y = 5;
} |
class Cat
{
int x; int y;
public Cat() { super();
this.x = 5; this.y = 5;
}
} |
| 实际发生的情况如下 |
|
class Pet
{
int x = 5, y = 5;
int weight = 10;
Pet(int x, int y)
{
this.x = x; this.y = y;
}
}
class Cat extends Pet
{
int tailLength = 8;
int age;
Cat(int x, int y, int age)
{
super(x, y);
this.age = age;
}
} |
class Pet extends Object
{
int x;
int y;
int weight;
Pet(int x, int y)
{
//call of the base class's constructor
super();
//initialize variables
this.x = 5; this.y = 5; this.weight = 10;
//execute the constructor code
this.x = x; this.y = y;
}
}
class Cat extends Pet
{
int tailLength;
int age;
Cat(int x, int y, int age)
{
//call of the base class's constructor
super(x, y);
//initialize variables
this.tailLength = 8;
//execute the constructor code
this.age = age;
}
} |
“现在清楚多了:首先是基类,然后是构造方法外部的变量,然后是构造方法代码。”
“做得不错,阿米戈!就是这样!”
GO TO FULL VERSION