2013-09-25 14 views
9

Chcę wykonać wiele konstruktorów, podczas tworzenia pojedynczego obiektu. Na przykład, mam definicję klasy jak to-Jak wykonać wiele konstruktorów, podczas tworzenia pojedynczego obiektu

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"); 
    } 
} 

I staram się to osiągnąć za pomocą następującego kodu -

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); 
    } 
} 

Ale w tym przypadku jest to generowanie błędów takich jak -

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 

Dzięki

+0

Ten artykuł może być też pomocny: http: //www.yegor256. com/2015/05/28/one-primary-constructor.html – yegor256

Odpowiedz

12

Zastosowanie this() zamiast Prg() w swoich konstruktorów

+1

Och, dzięki. Szukałem słów kluczowych takich jak super, aby wskazać tę samą klasę. Ale nie próbowałem tego. Teraz działa. – CodeCrypt

2

Dzwoniąc inni konstruktorzy Użyj this() zamiast Prg()

3

Należy użyć this oświadczenie.

np.

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

Zastosowanie this zamiast 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

użycie this keyword.Full kod działa następująco

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); 
    } 
} 
Powiązane problemy