Merge pull request #10944 from thomasduxbury/BAEL-4986

BAEL-4986: Private constructors in Java
This commit is contained in:
Jonathan Cook 2021-06-27 12:59:44 +02:00 committed by GitHub
commit f808407f8f
5 changed files with 105 additions and 0 deletions

View File

@ -0,0 +1,39 @@
package com.baeldung.privateconstructors;
public class Employee {
private final String name;
private final int age;
private final String department;
private Employee(String name, int age, String department) {
this.name = name;
this.age = age;
this.department = department;
}
public static class Builder {
private String name;
private int age;
private String department;
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setAge(int age) {
this.age = age;
return this;
}
public Builder setDepartment(String department) {
this.department = department;
return this;
}
public Employee build() {
return new Employee(name, age, department);
}
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.privateconstructors;
public class PrivateConstructorClass {
private PrivateConstructorClass() {
// in the private constructor
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.privateconstructors;
public final class SingletonClass {
private static SingletonClass INSTANCE;
private String info = "Initial info class";
private SingletonClass() {
}
public static SingletonClass getInstance() {
if (INSTANCE == null) {
INSTANCE = new SingletonClass();
}
return INSTANCE;
}
// getters and setters
}

View File

@ -0,0 +1,16 @@
package com.baeldung.privateconstructors;
public class StringUtils {
private StringUtils() {
// this class cannot be instantiated
}
public static String toUpperCase(String s) {
return s.toUpperCase();
}
public static String toLowerCase(String s) {
return s.toLowerCase();
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.privateconstructors;
public class ValueTypeClass {
private final String value;
private final String type;
public ValueTypeClass(int x) {
this(Integer.toString(x), "int");
}
public ValueTypeClass(boolean x) {
this(Boolean.toString(x), "boolean");
}
private ValueTypeClass(String value, String type) {
this.value = value;
this.type = type;
}
// getters and setters
}