Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.
다른 종류의 객체들은 종종 일정 부분 공통점이 있다. 산악 자전거, 도로 자전거, 2인 자전거 모두 자전거의 특징을 공유한다. 그러나 각 자전거들은 차이점을 만드는 추가적인 특징을 정의한다. 2인 자전거는 시트와 손잡이가 2개 있고, 도로 자전거는 낮은 손잡이, 몇 산악 자전거는 낮은 기어비를 제공하기 위한 추가적인 체인 고리가 있다.
Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:
객체 지향 프로그래밍은 클래스들이 공통적으로 사용하는 상태와 행동을 다른 클래스와 상속하도록 허용한다. 예제에서 자전거는 산악 자전거, 도로 자전거, 2인 자전거의 슈퍼 클래스가 된다. 자바 프로그래밍 언어에서, 각 클래스들은 하나의 슈퍼 클래스를 가질 수 있고, 각 슈퍼 클래스들은 제한되지 않은 수의 하위 클래스를 가질 수 있다.
The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from:
하위 클래스를 생성하는 구문은 간단하다. 당신의 클래스를 선언할 때, extends 키워드를 사용하여 상속할 클래스를 작성해준다.
class MountainBike extends Bicycle {
// new fields and methods defining
// a mountain bike would go here
}
This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass.
이것은 자전거와 필드와 메서드가 같은 산악 자전거를 제공한다. 그럼에도 이 코드가 이것을 고유하게 만드는 기능에 집중할 수 있게 한다.