2016-08-19 48 views
-1

我在构造函数中练习'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(); 
    } 
} 
+5

'但是,什么是它的实际使用time.'你可以澄清你真的想知道这里或者你有什么很难理解? – SomeJavaGuy

回答

-1

的输出将是:

Inside Constructor with String parameter as JBT 
Inside Constructor without parameter 

因为this("JBT")将调用构造与String参数

0

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

嗯,你可以,如果你想打电话从 基类或超类的构造函数,那么你可以使用super关键字使用关键字来从另一个调用 构造同一类的一个构造。在其他地方调用一个 构造函数称为Java中的构造函数链。

例子:

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 
1

在现实生活中,你主要用它设置默认值(就像你在你的例子一样),这样您可以简化用户的分类界面。

很多时候,这也是需要的,当一个班级随着时间的推移而发展并且您添加了一些新的功能。试想一下:

// 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 

现在,在以后的日子,你想一个很酷的新切换的功能添加到测试,因此您改变构造函数:

public Test(String someParam, boolean useCoolNewFeature) 

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

但是,如果您还提供旧的建设浅析签名,一切都会好起来的:

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