상속이란 무엇인가?에서 사용한 Bicycle 클래스와 MountainBike같은 하위클래스가 있다.
아래 이식가능한 Bicycle 클래스가 있다.
public class Bicycle {
// the Bicycle class has
// three fields
public int cadence;
public int gear;
public int speed;
// the Bicycle class has
// one constructor
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
// the Bicycle class has
// four methods
public void setCadence(int newValue) {
cadence = newValue;
}
public void setGear(int newValue) {
gear = newValue;
}
public void applyBrake(int decrement) {
speed -= decrement;
}
public void speedUp(int increment) {
speed += increment;
}
}
Bicycle을 상속받는 MountainBike 클래스는 다음과 같다.
public class MountainBike extends Bicycle {
// the MountainBike subclass has
// one field
public int seatHeight;
// the MountainBike subclass has
// one constructor
public MountainBike(int startHeight, int startCadence,
int startSpeed, int startGear) {
super(startCadence, startSpeed, startGear);
seatHeight = startHeight;
}
// the MountainBike subclass has
// one method
public void setHeight(int newValue) {
seatHeight = newValue;
}
}
MountainBike 클래스는 Bicycle의 모든 필드와 메서드를 상속받고, seatHeight라는 필드와 seatHeight를 설정하는 메서드를 추가했다.
출처
https://docs.oracle.com/javase/tutorial/java/javaOO/classes.html
클래스 선언은 아래와 같이 하면 된다.
class MyClass {
//field, constructor, and
// method declarations
}
중괄호 사이에 있는 클래스 바디에는 클래스에서 생성된 객체의 생명 주기에 필요한 것을 포함한다.
(새 객체를 초기화하기 위한 생성자, 클래스 및 객체의 상태를 제공하는 필드 선언, 클래스 및 해당 객체의 동작을 구현하는 메서드가 있다.)
클래스를 선언하는 시작부분에는 superclass와 interface 같은 정보를 포함할 수 있다.
class MyClass extends MySuperClass implements YourInterFace {
// field, constructor, and
// method declarations
}
이 코드는 MySuperClass의 subclass이고, YourInterFace 인터페이스를 상속받는다.
클래스 선언에는 아래 구성 요소가 순서대로 포함된다.
1. public, private 같은 접근제한자
2. 규칙에 따라 첫 글자가 대문자인 클래스 이름
3. 클래스의 부모클래스(superclass)가 있으면 클래스 이름 뒤에 extends 키워드가 추가
하위 클래스는 하나의 부모클래스만 확장할 수 있다.
4. 인터페이스를 구현한 클래스인 경우, implements 키워드가 추가
클래스는 둘 이상의 인터페이스를 구현할 수 있다.
5. 중괄호{}로 둘러진 클래스 바디
출처
https://docs.oracle.com/javase/tutorial/java/javaOO/classdecl.html