标签:his play 区别 print stat div lap pre 年龄
可能为一个类写了多个构造器,有时可能想在一个构造器里面调用另外一个构造器,为了减少代码的重复,可用this关键字做到这一点。
1 public class Flower { 2 private String string; 3 private int age; 4 5 public Flower() { 6 // 先调用public Flower(String string, int age) 7 this("leon", 120); 8 // 先调用public Flower(String string, int age) 9 } 10 public Flower(String string) { 11 this(string, 12); 12 } 13 14 public Flower(String string, int age) { 15 this.string = string; 16 this.age = age; 17 System.out.println("姓名:" + this.string + " 年龄: " + this.age); 18 } 19 20 public static void main(String[] args) { 21 Flower flower = new Flower(); 22 Flower flower1 = new Flower("leon"); 23 Flower flower2 = new Flower("leon", 12); 24 } 25 }
其实可以从结果看见,这其实可普通的函数调用没什么区别,只不过是用了this这个关键字。
标签:his play 区别 print stat div lap pre 年龄
原文地址:https://www.cnblogs.com/xpeanut/p/12863070.html