打个比方:
现在有某个类中存在多个构造方法,但是不管有多少个构造方法,最终结果都要打印一句“A”,不通过this()方法:- public class demo1 {
- private String name;
- private int age;
- public demo1(){
- System.out.print("A");
- }
- public demo1(String name){
- System.out.print("A");
- this.name=name;
- }
- public demo1(String name,int age){
- System.out.print("A");
- this.name=name;
- this.age=age;
- }
- //.....
- public String get(){
- return name+age;
- }
- public static void main(String[] args) throws Exception {
- demo1 d=new demo1("张三",20);
- System.out.print(d.get());
- }
- }
复制代码 通过this()方法实现- public class demo1 {
- private String name;
- private int age;
- public demo1(){
- System.out.print("A");
- }
- public demo1(String name){
- //System.out.print("A");
- this();
- this.name=name;
- }
- public demo1(String name,int age){
- //System.out.print("A");
- //this.name=name;
- this();
- this.age=age;
- }
- //.....
- public String get(){
- return name+age;
- }
- public static void main(String[] args) throws Exception {
- demo1 d=new demo1("张三",20);
- System.out.print(d.get());
- }
- }
复制代码 这个时候的this()就可以为我们做到代码优化的作用 |