使用显式构造函数调用



我在构造函数中练习'this'关键字。我知道"this"将有助于显式地调用构造函数。但是它在实时中有什么用呢?

显式构造函数调用。

class JBT {
    JBT() {
        this("JBT");
        System.out.println("Inside Constructor without parameter");
    }
    JBT(String str) {
        System.out
                .println("Inside Constructor with String parameter as " + str);
    }
    public static void main(String[] args) {
        JBT obj = new JBT();
    }
}

在实际生活中,您主要使用它来设置默认值(就像您在示例中所做的那样),以便您可以为用户简化类的接口。

通常,当一个类随着时间的推移而发展并且您添加了一些新特性时,这也是需要的。想想看:

// First version of "Test" class
public class Test {
     public Test(String someParam) {
         ...
     }
}
// use of the class
Test t = new Test("Hello World");  // all is fine
现在,在稍后的日期,您希望向Test添加一个很酷的新可切换特性,因此您将构造函数更改为:
public Test(String someParam, boolean useCoolNewFeature)

现在,原来的客户端代码将不再编译,这是

但是,如果您另外提供旧结构签名,则一切正常:

public Test(String someParam) {
    this(someParam, false); // cool new feature defaults to "off"
}

this返回当前实例/对象的引用。

你可以使用这个关键字从一个构造函数调用另一个构造函数的构造函数调用同一类的构造函数基类或超类,那么你可以使用super关键字。调用一个

的例子:

public class ChainingDemo {
   //default constructor of the class
   public ChainingDemo(){
         System.out.println("Default constructor");
   }
   public ChainingDemo(String str){
         this();
         System.out.println("Parametrized constructor with single param");
   }
   public ChainingDemo(String str, int num){
         //It will call the constructor with String argument
         this("Hello"); 
         System.out.println("Parametrized constructor with double args");
   }
   public ChainingDemo(int num1, int num2, int num3){
    // It will call the constructor with (String, integer) arguments
        this("Hello", 2);
        System.out.println("Parametrized constructor with three args");
   }
   public static void main(String args[]){
        //Creating an object using Constructor with 3 int arguments
        ChainingDemo obj = new ChainingDemo(5,5,15);
   }
}
输出:

Default constructor
Parametrized constructor with single param
Parametrized constructor with double args
Parametrized constructor with three args

输出将为:

Inside Constructor with String parameter as JBT
Inside Constructor without parameter

因为this("JBT")将调用带有String参数的构造函数

最新更新