Java에서 다른 생성자를 다른 생성자를 호출하려면 어떻게합니까?
질문
다른 클래스에서 다른 클래스 내에서 생성자를 호출 할 수 있습니까?그렇다면 어떻게?그리고 다른 생성자를 호출하는 가장 좋은 방법은 무엇입니까 (그것을 할 수있는 몇 가지 방법이있는 경우)?
답변
예, 가능합니다 :
public class Foo {
private int x;
public Foo() {
this(1);
}
public Foo(int x) {
this.x = x;
}
}
동일한 클래스에있는 대신 특정 수퍼 클래스 생성자를 체인하려면이 대신 슈퍼를 사용하십시오.하나의 생성자에만 체인 할 수 있으며 생성자 본문에서 첫 번째 명령문이어야합니다.
C #에 관한이 관련 질문을 참조하십시오. 그러나 동일한 원칙이 적용되는 경우.
답변
이 (args)를 사용합니다.기본 패턴은 가장 작은 생성자에서 가장 큰 것으로 작동하는 것입니다.
public class Cons {
public Cons() {
// A no arguments constructor that sends default values to the largest
this(madeUpArg1Value,madeUpArg2Value,madeUpArg3Value);
}
public Cons(int arg1, int arg2) {
// An example of a partial constructor that uses the passed in arguments
// and sends a hidden default value to the largest
this(arg1,arg2, madeUpArg3Value);
}
// Largest constructor that does the work
public Cons(int arg1, int arg2, int arg3) {
this.arg1 = arg1;
this.arg2 = arg2;
this.arg3 = arg3;
}
}
또한 밸류의보다 최근에 옹호하는 접근 방식을 사용할 수도 있고 "의": ":
public class Cons {
public static Cons newCons(int arg1,...) {
// This function is commonly called valueOf, like Integer.valueOf(..)
// More recently called "of", like EnumSet.of(..)
Cons c = new Cons(...);
c.setArg1(....);
return c;
}
}
수퍼 클래스를 호출하려면 슈퍼 (Somevalue)를 사용하십시오.슈퍼 호출은 생성자의 첫 번째 호출이어야하며 컴파일러 오류가 발생합니다.
답변
이 키워드를 사용하여 동일한 클래스 내의 다른 생성자에서 하나의 생성자를 호출 할 수 있습니다.
예시 :-
public class Example {
private String name;
public Example() {
this("Mahesh");
}
public Example(String name) {
this.name = name;
}
}
답변
[참고 : 다른 답변에서 보지 못했던 한 측면을 추가하고 싶습니다.이 ()가 첫 번째 줄에 있어야한다는 요구 사항의 한계를 극복하는 방법).]
Java에서 동일한 클래스의 다른 생성자는이 ()를 통해 생성자에서 호출 할 수 있습니다.그러나 이것은 첫 번째 줄에 있어야합니다.
public class MyClass {
public MyClass(double argument1, double argument2) {
this(argument1, argument2, 0.0);
}
public MyClass(double argument1, double argument2, double argument3) {
this.argument1 = argument1;
this.argument2 = argument2;
this.argument3 = argument3;
}
}
이것이 첫 번째 줄에 나타나야한다는 것은 큰 한계와 같지만 정적 메소드를 통해 다른 생성자의 인수를 생성 할 수 있습니다.예를 들어:
public class MyClass {
public MyClass(double argument1, double argument2) {
this(argument1, argument2, getDefaultArg3(argument1, argument2));
}
public MyClass(double argument1, double argument2, double argument3) {
this.argument1 = argument1;
this.argument2 = argument2;
this.argument3 = argument3;
}
private static double getDefaultArg3(double argument1, double argument2) {
double argument3 = 0;
// Calculate argument3 here if you like.
return argument3;
}
}
답변
예, 다른 생성자에서 생성자를 호출 할 수 있습니다.예를 들어:
public class Animal {
private int animalType;
public Animal() {
this(1); //here this(1) internally make call to Animal(1);
}
public Animal(int animalType) {
this.animalType = animalType;
}
}
자세한 내용을 읽을 수도 있습니다 Java에서 체인 생성자
답변
복잡한 건설의 필요성을 충당하는 디자인 패턴이 있습니다. - 간결하게 수행 할 수없는 경우 공장 방식이나 팩토리 클래스를 만듭니다.
최신 Java와 Lambdas 추가를 사용하면 원하는 초기화 코드를 수락 할 수있는 생성자를 만들 수 있습니다.
class LambdaInitedClass {
public LamdaInitedClass(Consumer<LambdaInitedClass> init) {
init.accept(this);
}
}
...로 전화 해.
new LambdaInitedClass(l -> { // init l any way you want });
출처:https://stackoverflow.com/questions/285177/how-do-i-call-one-constructor-from-another-in-java
최근댓글