1 / 33
文档名称:

j04 初始化与清除.ppt

格式:ppt   大小:835KB   页数:33页
下载后只包含 1 个 PPT 格式的文档,没有任何的图纸或源代码,查看文件列表

如果您已付费下载过本站文档,您可以点这里二次下载

分享

预览

j04 初始化与清除.ppt

上传人:373116296 2018/8/10 文件大小:835 KB

下载得到文件列表

j04 初始化与清除.ppt

相关文档

文档介绍

文档介绍:初始化和清理
******@.
2018/8/10
2
初始化和清理
Java用构造器确保正确的初始化,使用垃圾收集器进行清理。
2018/8/10
3
用构造器确保初始化
initialize() –必须记住去调用。
构造器
class Rock {
Rock() { //构造器
("Creating Rock");
}
}
public class SimpleConstructor {
public static void main(String args[]) {
for(int i = 0; i < 10; i++)
new Rock();
}
}
和类名相同,首字母大写。
2018/8/10
4
构造器
class Rock2 {
Rock2(int i) { //构造器
("Creating Rock number “+ i);
}
}
public class SimpleConstructor2 {
public static void main(String args[]) {
for(int i = 0; i < 10; i++)
new Rock2(i);
}
}
2018/8/10
5
细微区别
从上下文中推断意思
“Wash the shirt”(洗衬衫)
“Wash the car”(洗车)
“Wash the dog”(洗狗)
而非
“shirtWash the shirt”(以洗衬衫的方式洗衬衫)
“carWash the car”(以洗车的方式洗车)
“dogWash the dog”(以洗狗的方式洗狗)
2018/8/10
6
方法重载(overloading)
void wash (Shirt s) { // …
void wash (Car c) { // …
void wash (Dog d) { // …
唯一的参数组合来区别重载的方法。
2018/8/10
7
class Tree {
int height;
Tree() {
("Planting a seedling");
height = 0;
}
Tree(int i) {
(
"Creating new Tree that is "
+ i + " feet tall");
height = i;
}
方法重载–构造器
一个词,多个意思: overloaded
2018/8/10
8
方法重载–普通方法
void info() {
("Tree is “
+ height + " feet tall");
}
void info(String s) {
(s + ": Tree is "
+ height + " feet tall");
}
}
2018/8/10
9
方法重载–续
public class Overloading {
public static void main(String[] args) {
for(int i = 0; i < 5; i++) {
Tree t = new Tree(i = pRand(10));
();
("overloaded method");
}
// Overloaded constructor:
new Tree();
}
}
2018/8/10
10
涉及基本类型的重载
基本类型能从一个“较小”的类型自动提升至一个“较大”的类型
如果传入的实际参数大于重载方法的形式参数,就得通过转型来执行窄化转换。
如果不这样做,编译器就会报错。
窄化转换