–BAEL-4986: Private constructors in Java

This commit is contained in:
Thomas Duxbury 2021-06-01 19:41:51 +01:00
parent d0d0f71518
commit a75cc22181
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() {
System.out.println("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() {
System.out.println("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
}