자바에서 상속은 주로 동적 바인딩을 하려고 사용함
예제
package ex06;
class Animal {
int age;
void eat() {
System.out.println("먹고 있음...");
}
}
class Dog extends Animal {
void bark() {
System.out.println("짖고 있음...");
}
}
public class DogTest {
public static void main(String[] args) {
Dog d = new Dog();
d.bark();
d.eat();
}
}
package ex06;
// 부모가 있다면 부모 생성자를 호출하여 힙에 먼저 띄운다
class Shape {
int x, y;
public Shape() {
System.out.println("Shape 생성됨");
}
}
class Circle extends Shape {
int radius; // 반지름
public Circle(int radius) {
System.out.println("Circle 생성됨");
this.radius = radius;
super.x = 0; // 자식이 부모에게 접근할때 super.를 쓴다
super.y = 0;
}
double getArea() {
return 3.14 * radius * radius;
}
}
public class CircleTest {
public static void main(String[] args) {
Circle circle = new Circle(10);
circle.getArea();
}
}
상속과 생성자
package ex06;
class Person {
String name;
public Person() {
}
public Person(String theName) {
this.name = theName;
}
}
class Employee extends Person {
String id;
public Employee() {
super();
}
public Employee(String name) {
super(name);
}
public Employee(String name, String id) {
super(name);
this.id = id;
}
public String toString() {
return "Employee [id=" + id + " name="+name+"]";
}
}
public class EmployeeTest {
public static void main(String[] args) {
Employee e = new Employee("kim", "20210001");
System.out.println(e);
}
}
메소드 오버라이딩(재정의)
<aside> 💡 오버로딩 = 같은 메소드명을 가진 여러 개의 메소드를 작성하는것.
오버라이딩 = 부모 클래스의 메소드를 자식 클래스가 다시 정의하는 것.
</aside>
자식 클래스가 부모 클래스의 메소드를 자신의 필요에 맞추어서 재정의하는 것
이때 메소드의 이름이나 매개 변수, 반환형은 동일하여야 한다.
자식 객체에서 해당 메소드를 실행하면 오버라이딩된 메소드가 실행된다.
package ex06;
class Shape02 {
public void draw() {
System.out.println("Shape");
}
}
class Circle02 extends Shape02 {
public void draw() {
System.out.println("Circle02");
}
}
class Rectangle extends Shape02 {
public void draw() {
System.out.println("Rectangle");
}
}
class Triangle extends Shape02 {
public void draw() {
System.out.println("Triangle");
}
}
public class ShapeTest {
public static void main(String[] args) {
Triangle t = new Triangle();
t.draw();
}
}
//Triangle