Более одного конструктора в классе [требует правки]

268
05 июня 2017, 22:32

Как можно написать два конструктора для одного класса?

Answer 1

Например так?

class Test {
    private int param1 = 0;
    public Test() {
    }
    public Test(int param1) {
        this.param1 = param1;
    }
}
public static void main (String[] args) throws java.lang.Exception
{       
    new Test();
    new Test(666);
}

Конструкторы можно перегружать по аналогии с обычными методами.

Answer 2

Возможность указать в одном классе несколько конструкторов (или в общем смысле - методов с одинаковым названием) называется перегрузкой. Название у всех конструкторов в данном случае одинаковое, а вот типы и количество принимаемых параметров обязательно должны отличаться.

public class Constructor{

    public Constructor(){//вариант 1
      //что-то делаем без параметров
    }
    public Constructor(String string){//вариант 2
      //что-то делаем со строкой string
    }
    public Constructor(String string, Integer integer){//вариант 3
      //что-то делаем со строкой string и числовым значением integer
    }
    //и так далее. Главное разные типы и/или количество параметров
}

Создаем новый экземпляр класса Constructor

Constructor construct = new Constructor();//вариант 1
Constructor construct = new Constructor("Я строка!!!");//вариант 2
Constructor construct = new Constructor("Я строка!!!", 100500);//вариант 3
Answer 3

Также как и обычные перегруженныые методы.

public class Test {
    private int firstProperty;
    private float secondProperty;
    private boolean thirdProperty;
    private char fourthProperty;
    private String fifthProperty;
    private byte sixthProperty;
    private Object seventhProperty;
    private Long eighthProperty;
    private Double ninthProperty;
    private Short tenthProperty;
    public Test() {
    }

    public Test(int firstProperty, float secondProperty) {
        this.firstProperty = firstProperty;
        this.secondProperty = secondProperty;
    }
    public Test(int firstProperty, boolean thirdProperty) {
        this.firstProperty = firstProperty;
        this.thirdProperty = thirdProperty;
    }
    public Test(Double ninthProperty, Short tenthProperty) {
        this.ninthProperty = ninthProperty;
        this.tenthProperty = tenthProperty;
    }
    public Test(int firstProperty, float secondProperty, boolean thirdProperty) {
        this.firstProperty = firstProperty;
        this.secondProperty = secondProperty;
        this.thirdProperty = thirdProperty;
    }
    public Test(int firstProperty, float secondProperty, boolean thirdProperty, char fourthProperty) {
        this.firstProperty = firstProperty;
        this.secondProperty = secondProperty;
        this.thirdProperty = thirdProperty;
        this.fourthProperty = fourthProperty;
    }
    // ...
    public Test(int firstProperty, float secondProperty, boolean thirdProperty, char fourthProperty, String fifthProperty, byte sixthProperty, Object seventhProperty, Long eighthProperty, Double ninthProperty, Short tenthProperty) {
        this.firstProperty = firstProperty;
        this.secondProperty = secondProperty;
        this.thirdProperty = thirdProperty;
        this.fourthProperty = fourthProperty;
        this.fifthProperty = fifthProperty;
        this.sixthProperty = sixthProperty;
        this.seventhProperty = seventhProperty;
        this.eighthProperty = eighthProperty;
        this.ninthProperty = ninthProperty;
        this.tenthProperty = tenthProperty;
    }
}

Перегрузка методов класса в Java

Java SE: Урок 27. Перегрузка методов

READ ALSO
Как получить JSON из CURL запроса?

Как получить JSON из CURL запроса?

У меня имеется следующий пример CURL запроса

255
Парсинг Json, почему не работает?

Парсинг Json, почему не работает?

Что я сделал не так?

349
Защита apk от декомпиляции

Защита apk от декомпиляции

Подскажите самые простые из существующих методов защиты для скрытия (шифровки, нечитаемости и пр) хотябы одного файла strings

327