如何使用this在构造器中调用构造器?
如何使用this在构造器中调用构造器?
可能为一个类写了多个构造器,有时可能想在一个构造器中调用另一个构造器,以避免重复代码。可用this关键字做到这一点。更多进入考试大计算机java认证试题、真题、模拟题、辅导等。 通常写this的时候,都是指“这个对象”或者“当前对象”,而且它本身表示对当前对象的引用。
在构造器中,如果为this添加了参数列表,那么就有了不同的含义。这将产生对符合此参数列表的某个构造器的明确调用;这样,调用其他构造器就有了直接的途径: Java代码 public class Flower{ int petalCount=0; String s="initial value"; Flower(int petals){ petalCount=petals; System。
out。print("Constructor w/int arg only,petalCount=。。"+petalCount); } Flower(String ss){ System。out。print("Constructor w/String arg only,s="+ss); s=ss; }。