2013-09-25 6 views
9

Ich möchte mehrere Konstruktoren ausführen, während ich ein einzelnes Objekt erstelle. Zum Beispiel habe ich eine Klassendefinition wie this-So führen Sie mehrere Konstruktoren aus, wenn Sie ein einzelnes Objekt erstellen

public class Prg 
{ 
    public Prg() 
    { 
     System.out.println("In default constructor"); 
    } 
    public Prg(int a) 
    { 
     System.out.println("In single parameter constructor"); 
    } 
    public Prg(int b, int c) 
    { 
     System.out.println("In multiple parameter constructor"); 
    } 
} 

Und ich versuche es durch den folgenden Code zu erreichen -

public class Prg 
{ 
    public Prg() 
    { 
     System.out.println("In default constructor"); 
    } 
    public Prg(int a) 
    { 
     Prg(); 
     System.out.println("In single parameter constructor"); 
    } 
    public Prg(int b, int c) 
    { 
     Prg(b); 
     System.out.println("In multiple parameter constructor"); 
    } 
    public static void main(String s[]) 
    { 
     Prg obj = new Prg(10, 20); 
    } 
} 

Aber in diesem Fall ist es erzeugt Fehler wie -

Prg.java:11: error: cannot find symbol 
      Prg(); 
      ^
    symbol: method Prg() 
    location: class Prg 
Prg.java:16: error: cannot find symbol 
      Prg(b); 
      ^
    symbol: method Prg(int) 
    location: class Prg 
2 errors 

Dank

+0

dieser Artikel kann auch hilfreich sein: http: //www.yegor256. com/2015/05/28/one-primary-constructor.html – yegor256

Antwort

12

Verwenden this() statt Prg() in der Konstrukteurs-

+1

Oh, danke. Ich suchte nach Schlüsselwörtern wie super, um dieselbe Klasse zu zeigen. Aber ich habe das nicht versucht. Jetzt geht es. – CodeCrypt

2

Beim Aufruf andere Konstrukteure verwenden this() statt Prg()

3

Sie this Anweisung verwenden soll.

z.B.

public Prg(int b, int c) 
{ 
    this(b); 
    System.out.println("In multiple parameter constructor"); 
} 
5

Verwenden this statt Prg

public Prg() 
    { 
     System.out.println("In default constructor"); 
    } 
    public Prg(int a) 
    { 
     this(); 
     System.out.println("In single parameter constructor"); 
    } 
    public Prg(int b, int c) 
    { 
     this(b); 
     System.out.println("In multiple parameter constructor"); 
    } 
3

Verwendung this keyword.Full Code ausgeführt wird, wie folgt

public class Prg 
{ 
    public Prg() 
    { 
     System.out.println("In default constructor"); 
    } 
    public Prg(int a) 
    { 
     this(); 
     System.out.println("In single parameter constructor"); 
    } 
    public Prg(int b, int c) 
    { 
     //Prg obj = new Prg(10, 20); 

this(b);  System.out.println("In multiple parameter constructor"); 
    } 
    public static void main(String s[]) 
    { 
     Prg obj = new Prg(10, 20); 
    } 
} 
Verwandte Themen