JAVA 상속

박승현·2022년 3월 26일
0

JAVA

목록 보기
9/16

상속

상속 이란 새로운 클래스를 작성할때 기존에 존재하는 클래스를 물려받아 이용한다. 기존의 클래스가 가진 멤버를 물려받기 때문에 새롭게 작성해야 할 코드의 양이 줄어드는 효과가 있다. 이때 자신의 멤버를 물려주는 클래스를 부모클래스라고 하고 상속받는 클래스를 자식 클래스라고 한다.

  • 상속할 때는 새롭게 작성할 클래스 선언 부분 뒤에 'extends 부모 클래스 이름'을 붙인다.
  • 단일 상속만 허용한다.
  • 클래스 앞에 final이 붙은 경우는 상속이 불가능 하다.
class Person {
	void breath() {
		System.out.println("숨쉬기");
	}
	void eat() {
		System.out.println("밥먹기");
	}
	void say() {
		System.out.println("말하기");
	}
}

class Student extends Person {
	
	void learn() {
		System.out.println("배우기");
	}

}

class Teacher extends Person {
	
	void teath() {
		System.out.println("가르치기");
	}
	
}
public class Inheritance1 {

	
	public static void main(String[] args) {
		Student s1 = new Student();
		s1.breath();
		s1.learn();
		
		Teacher t1 = new Teacher();
		t1.eat();
		t1.teath();
	}

}
// Parents 클래스의 멤버들을 상속받음

오버라이딩

오버라이딩은 자식 클래스에서 부모 클래스로부터 물려받아 메서드를 재정의 하는것을 말한다.

class Parents {
	void method1() {
		// 부모 클래스의 메서드
	}
}

class Child extends Parents {
	@Override
	void method1() {
		//자식 클래스에서 메서드 내용 재정의
	}
}
  • 오버라이딩 하는 이유는 부모클래스로 부터 상속받았지만 자식클래스에서 부모와는 다르게 동작해야 될 때도 있기 때문이다.

super()

부모 클래스의 생성자 호출은 상위 클래스를 의미하는 super라는 키워드에 ()를 붙인 super()을 통해 이루어진다. 부모 클래스 호출은 무조건 자식 클래스 생성자 첫 줄에서 이루어진다. 만약 자식의 생성자 내부에 부모 클래스의 생성자를 따라 작성하지 않았다면 자동적을 컴파일러는 자식 클래스의 생성자 첫 줄에 super();을 추가한다.

class Car{
	int wheel;
	int speed;
	String color;
	
	Car(String color){
		this.color = color;
	}
}

class SportsCar extends Car{

	int speedLimit;
	
	SportsCar(String color, int speedLimit) {
		super(color); // 상위 클래스의 생성자
		this.speedLimit = speedLimit;
	}
}

public class SuperConstructor {

	public static void main(String[] args) {
		SportsCar sportsCar = new SportsCar("red", 330);
		
		System.out.println(sportsCar.color);
		System.out.println(sportsCar.speedLimit);
	}
}
profile
그냥 해보자 안되더라도 해보자 끝까지 해보자

0개의 댓글

관련 채용 정보