【问题标题】:using "this" in java [duplicate]在java中使用“this”[重复]
【发布时间】:2014-08-15 10:58:22
【问题描述】:

你好,我对 java 还是有点陌生​​。当涉及到实例变量时,我得到了“this”的概念,但是当我在没有参数的构造函数中使用它时,我有点困惑。所以我的问题是这样的事情是如何工作的?

private double x;
private double y;

public static final double EPSILON = 1e-5;
public static boolean debug = false;


public Point(double x, double y){
    this.x=x;
    this.y=y;  // Done sets the x,y private types to the x,y type provided in the ()
}

public Point(){
    this(0.0,0.0);  //Sets, x and y to doubles of 0.0,0.0?? 
}                   //How does this work? 

我的 point() 构造函数会通过调用点 (x,y) 构造函数来创建 (0.0,0.0) 的原点吗?对此的任何澄清都会对我有很大帮助!

【问题讨论】:

  • “我的 point() 构造函数会通过调用点 (x,y) 构造函数来创建 (0.0,0.0) 的原点吗?” - 是的,这就是重点。 this(...) 允许您将构造函数调用链接在一起以确保对象在创建时的状态

标签: java this


【解决方案1】:

this(arguments) 是一种仅在构造函数中可用的特殊语法。它所做的是使用给定的参数调用 another 构造函数。因此,调用this(0.0, 0.0) 将调用构造函数Point(double, double),其值为(0.0, 0.0)。反过来,这会将xy 设置为0.0

【讨论】:

    【解决方案2】:

    当调用this() 时,您将该构造函数的调用重定向到另一个构造函数(在本例中为第一个构造函数)。所以你创建了一个Point (0,0)。

    你基本上说,每当有人调用new Point(),它就会被Java替换为new Point(0.0,0.0)


    有时做相反的事情会很有用(调用具有较少参数的构造函数)。在这种情况下,每个构造函数只处理其附加参数,这些参数更倾向于“关注点分离”。

    例如:

    public class Point {
    
        private double x = 0.0d;
        private double y = 0.0d;
    
        public Point () {
        }
    
        public Point (double x) {
            this();
            this.x = x;
        }
    
        public Point (double x, double y) {
            this(x);
            this.y = y;
        }
    
    }
    

    【讨论】:

      【解决方案3】:

      Poine() 将用 0.0 初始化 x 和 y

      Point(double x, double y) 将在函数的参数中使用 x 和 y 来初始化 x 和 y。

      Point(double x, double y) 中的 this 是 Point 类的指针

      在 Point() 中,您可以将其视为 Point 类的构造函数,它将

      调用 Point(double x , double y)。

      【讨论】:

        猜你喜欢
        • 2010-10-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-26
        • 2012-04-15
        • 2017-05-29
        相关资源
        最近更新 更多