Room of Requirment

Less is More


  • Home

  • Tags

  • Categories

  • Archives

Java Initialization

Posted on 2019-08-31 Edited on 2019-09-01

用构造器确保初始化

概念: 在创建对象时被自动调用的特殊方法,并额外提供了“垃圾回收器”。对于不再使用的内存资源,垃圾回收器能将它自动释放。
不接受任何参数的构造器叫做默认构造器,Java文档中通常使用术语无参构造器。但是和其他方法一样,构造器也能带有形式参数,以便指定如何创建对象。如果Tree(int)是Tree类中唯一的构造器,那么编译器将不会允许你以其他任何方法创建Tree对象。在Java中,“初始化”和“创建”捆绑在一起,两者不能分离。构造器本身并没有任何返回值。

方法重载

任何程序设计语言都具备的一项重要特性就是对名字的运用。当创建一个对象时,也就给此对象分配到的存储空间取了一个名字。在Java里,构造器是强制重载方法名的另一个原因。既然构造器的名字已经由类名决定,就只能有一个构造器名。为了让方法名相同而形式参数不同的构造器同时存在,必须要用到方法重载。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import static net.midview.util.Print.*;

class Tree{
int height;
Tree(){
print("Planting a seedling");
height = 0;
}
Tree(int initialHeight){
height = initialHeight:
print("Creating new Tree that is " + height + " feet tall");
}
void info(){
print("Tree is " + height + "feet tall");
}
void info(String s){
print(s + ": Tree is " + height + " feet tall");
}
}

有了方法重载,可以为两者使用相同的名字

区分重载方法

重载的方法通过独一无二的参数类型列表去让Java便于区分,甚至参数顺序不同也足以区分两个方法。不过一般情况下别这么做,因为这会使代码难以维护

1
2
3
4
public class OverloadingOrder{
static void f(String s, int i){}
static void f(int i, String s){}
}

涉及基本类型的重载

byte8位,short16位,int32位,long64位,float单精度32位,double双精度64位,char单一的16位Unicode字符
基本类型能从一个“较小”的类型自动提升至一个“较大”的类型。如果传入的数据类型(实际参数类型)小于方法中声明的形式参数类型,实际数据类型就会被提升。char型略有不同,如果无法找到恰好接受char参数的方法,就会把char直接提升至int型。
如果传入的实际参数较大,就得通过类型转换来执行窄化转换。如果不这样做,编译器就会报错。

以返回值区分重载方法

根据方法的返回值来区分重载方法是行不通的。

默认构造器

如果你写的类中没有构造器,则编译器会自动帮你创建一个默认构造器。
如果已经定义了一个构造器(无论是否有参数),编译器就不会帮你自动创建默认构造器。

1
2
3
4
5
6
7
8
9
10
class Bird2{
Bird2(int i){}
Bird2(double d){}
}

public class NoSynthesis{
public static void main(String[] args){
//! Bird2 b = new Bird2(); //No default
}
}

如果按照上述编写会报错。

this关键字

1
2
3
4
5
6
7
8
9
10
class Peeler{
static Apple peel(Apple apple){
return apple;
}
}
class Apple{
Apple getPeeled(){
return Peeler.peel(this);
}
}

为了将自身传递给外部方法,Apple必须使用this关键字。
可能为一个类写了多个构造器,有时可能想在一个构造器中调用另一个构造器,以避免重复代码。可用this关键字做到这一点。
```java
public class Flower{
int petalCount = 0;
String s = “initial value”;
Flower(int petals){}
Flower(String ss){}
Flower(String s, int petals){
this(petals);
//! this(s); //Can’t call two!
this.s = s
}
}

# Initialization
Java 数组
CSE205W1_Introduction to the Internet
  • Table of Contents
  • Overview

2AM

they said the fruit never gon' fall far from the tree
14 posts
1 categories
7 tags
  1. 1. 用构造器确保初始化
  2. 2. 方法重载
    1. 2.1. 区分重载方法
    2. 2.2. 涉及基本类型的重载
    3. 2.3. 以返回值区分重载方法
  3. 3. 默认构造器
  4. 4. this关键字
© 2019 2AM
Powered by Hexo v3.9.0
|
Theme – NexT.Muse v7.3.0