Constructor usage guideline

private constructor는 정적 메소드와 필드 (static method & field)만 있는 경우 사용함.

class Counter {
private Counter() { }
public static int currentCount;
public static int IncrementCount() { return ++currentCount; }
}
class TestCounter
{
public static void main(String[] args)
{
// If you uncomment the following statement, it will generate
// an error because the constructor is inaccessible:
//Counter aCounter = new Counter(); // Error
Counter.currentCount = 100;
Counter.IncrementCount();
System.out.println(“count=” + Counter.currentCount);
}
}
// Output: New count: 101

protected constructor는 추상클래스 (abstract class)에서 사용을 권고함. 추상 클래스를 상속받는 파생클래스에서 파생 클래스 생성자가 부모 클래스 즉, 추상 클래스를 초기화 하기 위해 추상 클래스 생성자를 호출 할 수 있도록 지원함.

public abstract class Shape
{
protected Shape(String name) { this.name = name; }
private String name;
public void print() { System.out.print(this.name); }
}

public class Rectangle extends Shape
{
private double width, height;
public Rectangle(String name) { super(name); this.width = 2; this.height = 3; }
@Override
public void print()
{
super.print();
System.out.printf(” 가로: %f 세로: %f\n”, this.width, this.height);
}
}

public class Triangle extends Shape
{
private double bottom, height;
public Triangle(String name) { super(name); this.bottom = 1; this.height = 1; }
@Override
public void print()
{
super.print();
System.out.printf(” 밑변: %f 높이: %f\n”, this.bottom, this.height);
}
}

class ShapeTest
{
public static void main(String[] args)
{
//Shape s1 = new Shape(“도형”); // Error; Shape is abstract; cannot be instantiated
Shape s = new Triangle(“삼각형”);
s.print(); // 삼각형 밑변: 1 높이: 1
s = new Rectangle(“직사각형”);
s.print(); // 직사각형 가로: 2 세로: 3
}
}