Java“ this”在构造函数中 [英] Java "this" in constructors

查看:69
本文介绍了Java“ this”在构造函数中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常基本的问题,我从来没有用Java编写过代码,但我正在为一个朋友编写一个类……具有类似这样的东西:

Well, this is a very basic question, I've never coded in java, but I'm writing a class for a friend... Having something like:

class myClass{

    private string name;
    public string getName() {
        return this.name;
    }   
    public void setName (int newValue) {
        this.name = newValue;
    }

    private int number;
    public int getNumber() {
        return this.number;
    }   
    public void setNumber (int newValue) {
        this.number = newValue;
    }
}  

我想构建构造函数的方式是:

The way I was thinking of building the constructor was:

public myClass (string name, int numbers) {
    this.name = name;
    this.number = number;
}

我的问题:


  1. 我正在使用与参数相同的属性标识符。做这个。避免在这里遇到任何麻烦?

  2. 使用set方法更好吗?如果可以,我应该使用 this吗?

非常感谢

推荐答案


  1. 是的,它避免了名称冲突。在构造函数的上下文中,名称 name 表示参数,名称 this.name 表示实例字段

  2. 取决于您所说的更好。就个人而言,我会将 name number 字段定为final,因此该类是不可变的。以我的经验,最好从不可变的类定义开始,并且仅在有合理需要的情况下才转向可变的东西。

  1. Yes, it avoids the name clash. In the constructor's context, the name name refers to the parameter, and the name this.name refers to the instance field.
  2. Depends on what you mean by "better." Personally, I would make the name and number fields final, so the class is immutable. In my experience, it's better to start from an immutable class definition, and only move towards something mutable if there is a legitimate need to do so.

这篇关于Java“ this”在构造函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆