在从构造函数调用另一个构造函数时,通过“this”关键字引用类名如何将值设置为对象?[关闭]

How does referring to class name through 'this' keyword while calling another constructor from a constructor set values to an object? [closed]

提问人:Anurag-210 提问时间:4/24/2022 最后编辑:Turing85Anurag-210 更新时间:4/24/2022 访问量:78

问:


想改进这个问题吗?通过编辑这篇文章添加详细信息并澄清问题。

去年关闭。

当从构造函数调用构造函数时,我们使用“this”关键字。“this”关键字是指类名。那么,当我们只引用类而不是对象时,如何在对象中设置值呢?

Student random = new student();
class Student {
  int roll;

  student() {
    this student(13);
  }

  student(int roll) {
    this.roll = roll;
  }
}
Java OOP 构造函数 this

评论

1赞 Guy 4/24/2022
它应该是 ,而不是 .请注意,不是.this(13);this student (13);studentStudent
0赞 Turing85 4/24/2022
备注:构造函数的拼写必须始终与类名 ( -> ) 完全相同。student() { ... }Student() { ... }
0赞 user207421 4/24/2022
它通过引用另一个构造函数来设置对象中的值。你已经回答了自己的问题。但关键字并不“引用类名”。this

答:

0赞 Chetan Ahirrao 4/24/2022 #1

this关键字不引用类名。它指的是当前对象。它不是参考。static

1赞 theaniknath 4/24/2022 #2

看,您正在创建两个构造函数,其默认值为 13,另一个构造函数设置该值。更准确地说,如果没有给出任何值,则调用第一个构造函数,并使用默认值 13 调用第二个构造函数。Student()Student(int roll)

然后来到你的问题,我们可以使用从一个构造函数引用到另一个构造函数this

例如。

public class Car {
 boolean isStart;
 Car() { 
  this(true);
 }
 Car(boolean start) {
  if (start == true) 
   isStart = true;
 }
}

在这种情况下,例如,我们看到如果使用默认值调用,则使用布尔值调用其他构造函数。Car()

评论

0赞 Anurag-210 4/25/2022
在您的示例中,“this(true)”行,通常“this”是指我们调用构造函数的对象。但是我们通常不会用对象名来放置参数,而是用类名来放置它们。例如,“学生随机 = 新学生 (abc)”。这里我们不能放“random(abc)”。但是在“this(true)”行中,如果“this”被替换为 object,那么我们正在做类似“random(abc)”的事情,即用 object 放置参数。
0赞 theaniknath 4/25/2022
@Anurag-210 这将导致编译器错误