0

在以下程序中,我使用了 this(1) 和 this(2) 使用 this(1) 和 this(2) 的目的是什么,我还想知道这是关键字还是方法?我是新手java编程语言。

class Const
{
    Const()
    {
        this(1);
        System.out.println(1);

    }
    Const(int x)
    {
        System.out.println(2);
    }
}
class const1 extends Const
{
    int a;
    const1()
    {
        this(8);
        System.out.println(3);

    }
        const1(int x)
    {

        System.out.println(4);

    }
    public static void main(String s[])
    {
        new const1();
    }
}
4

3 回答 3

5

这些是替代的构造函数调用。它们调用同一类中的另一个构造函数。这允许多个构造函数共享相同的代码以实现共同行为。没有它,你有时会被迫重复自己。

例如:

Const()
{
    this(1);
    ...
}

使用实际参数“1”调用此构造函数:

Const(int x) { ... }

super()您可以以类似的方式使用关键字来调用超类构造函数。

来自 Java 语言规范,8.8.7.1,显式构造函数调用

显式构造函数调用语句可以分为两种:

备用构造函数调用以关键字 this 开头(可能以显式类型参数开头)。它们用于调用同一类的备用构造函数。

超类构造函数调用以关键字 super(可能以显式类型参数开头)或 Primary 表达式开头。它们用于调用直接超类的构造函数。

于 2013-07-31T17:56:35.363 回答
1

this()if 在构造函数中使用实际上是用来调用同一类的另一个构造函数。如果您保留重载的构造函数,这将特别有用。

public class Rectangle {
  private int x, y;
  private int width, height;

  public Rectangle() {
     this(0, 0, 0, 0);
  }
  public Rectangle(int width, int height) {
      this(0, 0, width, height);
  }
  public Rectangle(int x, int y, int width, int height) {
      this.x = x;
      this.y = y;
      this.width = width;
      this.height = height;
  }
...
}

记住, this()或者super()必须是构造函数中的第一条语句,如果你使用它们的话。因此它们不能在构造函数中一起使用。

this如果在方法体中使用,将引用调用该方法的当前实例。

阅读 Oracle 教程,了解这个super

于 2013-07-31T17:58:59.887 回答
0

它类似于为方法创建重载,因此它们模拟具有“可选”参数,例如:

DoStuff(int x, int y)
{
    //Stuff
}

DoStuff(int x)
{
    DoStuff(x, x);
}

除非您在构造函数中执行此操作(如果它们不传递值,只需使用值 1)。要回答这个问题this,需要调用对象的构造函数。

于 2013-07-31T17:59:42.813 回答