第5章(1) 构造器

构造器是一个在创建对象时被自动调用的特殊方法。

1. 构造器的命名

构造器采用与类相同的名称。这么做的意义在于:

(1). 避免与类的某个成员的名称冲突。

(2)让编译器自己知道应该调用那个方法。

2. 构造器是一种特殊的方法:

创建对象时,会为对象分配存储空间,同时调用相应的构造器,以确保对象得到恰当的初始化。

无参构造器又叫做默认构造器,当没有为类提供任何的构造器时,编译器会自动帮你创建一个默认构造器。当然我们也可以自己添加带参数的构造器,可以用于在初始化对象的时候提供参数。

注意下面的例子:

class Rock {
  Rock(int i) {
    System.out.println(
      "Creating Rock number " + i);
  }
}
 
public class SimpleConstructor {
  public static void main(String[] args) {
    for(int i = 0; i < 10; i++)
      new Rock(i);
  }
}

这时构造器可以接受参数来创建一个Rock对象。但同时,Rock(int)Rock类中唯一的构造器,编译器将不允许你以其他任何方式创建Rock对象,如new Rock()会有报错。

构建器属于一种较特殊的方法类型,因为它没有返回值new表达式确实返回了对新建对象的引用,但构造器本身并没有任何的返回值。

 

方法重载

为了让方法名相同而形式参数不同的构造器同时存在,必须用到方法重载。

每个重载的方法都必须有一个独一无二的参数类型列表。

注意:

(1). 对涉及基本类型的重载,方法接受较小的基本类型作为参数的时候,较小类型会向较大类型自动提升,这种情况可能造成一些混淆,如下面的例子:

存在void f(int),传入char型参数,如果找不到恰好接受char参数的方法,就会直接把char型提升为int型。

(2). 如果传入的实际参数较大,就得通过类型转换来执行窄化转换,否则编译器会报错。

this关键字

this关键字只能在方法内部使用,表示对“调用方法的那个对象”的引用。

this关键字对于将当前对象传递给其他方法也很有用:

class Person{
public void eat(Apple apple) {
Apple peeled = apple.getPeeled();
System.out.println("Yummy");
}
}
 
class Peeler {
static Apple peel(Apple apple) {
// ... remove peel
return apple; // Peeled
}
}
 
class Apple {
Apple getPeeled() {
return Peeler.peel(this);
}
}
public class PassingThis {
public static void main(String[] args) {
new Person().eat(new Apple());
}
}

这样的用法出现在peel这个方法应用于许多不同的类,而你有不想重复这些代码。

在构造器中调用构造器

如果为this添加了参数列表,那么就有了不同的含义。这将产生对符合此参数列表的某个构造器的明确调用

在构造器中可以用this调用一个构造器,且必须将构造器置于最起始位置,否则编译器会报错。除了构造器外,编译器禁止在其他任何方法中调用构造器。

实际应用看下面的例子:

//: Flower.java
// Calling constructors with "this"
 
public class Flower {
  private int petalCount = 0;
  private String s = new String("null");
  Flower(int petals) {
    petalCount = petals;
    System.out.println(
      "Constructor w/ int arg only, petalCount= "
      + petalCount);
  }
  Flower(String ss) {
    System.out.println(
      "Constructor w/ String arg only, s=" + ss);
    s = ss;
  }
  Flower(String s, int petals) {
    this(petals);
//!    this(s); // Can't call two!
    this.s = s; // Another use of "this"
    System.out.println("String & int args");
  }
  Flower() {
    this("hi", 47);
    System.out.println(
      "default constructor (no args)");
  }
  void print() {
//!    this(11); // Not inside non-constructor!
    System.out.println(
      "petalCount = " + petalCount + " s = "+ s);
  }
  public static void main(String[] args) {
    Flower x = new Flower();
    x.print();
  }
} ///:~


static的含义:

static方法就是没有this的方法,在static方法内部不能调用非静态方法,反过来倒是可以的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值