protected constructor

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 Triangle extends Shape
{
private double bottom, height;

public Triangle(String name) { super(name); this.bottom = 1; this.height = 1; }

public void print()
{
super.print();
System.out.printf(” 밑변: %f 높이: %f\n”, this.bottom, this.height);
}
}
public class Rectangle extends Shape
{
private double width, height;

public Rectangle(String name) { super(name); this.width = 2; this.height = 3; }

public void print()
{
super.print();
System.out.printf(” 가로: %f 세로: %f\n”, this.width, this.height);
}
}
class ShapeTest
{
public static void main(String[] args)
{
// Shape s = new Shape(“도형”); // Error; Shape is abstract; cannot be instantiated
Shape s = new Triangle(“삼각형”);
s.print(); // 삼각형 밑변: 1 높이: 1
s = new Rectangle(“직사각형”);
s.print(); // 직사각형 가로: 2 세로: 3
}
}