상위 클래스로부터 상속 받은 메서드의 내용을 하위 클래스에서 변경하는 것을 오버라이딩(Overriding)이라고 한다.
//부모 클래스의 참조 변수로 자식 인스턴스를 참조할 수 있다.
//오버로딩 : 메서드의 이름은 같지만 매개변수의 타입이나 개수가 다르면 다른 매서드로 간주한다.
//오버라이딩 : 메서드의 원형이 완벽히 같은 메서드의 정의 부분을 재정의 한다. => 상속에서 사용 부모클래스의 대부분의 기능이 일치하는 경우 일치하지 않은 기능만 재정의 해서 사용할 수 있다.
class Point{
int x;
int y;
String getLocation() {
return "x :" + x + ",y : " + y;
}
}
class point3D extends Point{
int z;
String getLocation() {
return "x :" + x + ",y : " + y + ",z : " + z;
}
}
public class _01_point {
public static void main(String[] args) {
point3D p1 = new point3D();
System.out.println(p1.getLocation());
}
}
Animal 클래스에는 makeSound 메서드가 있고, Dog 클래스에서는 makeSound 메서드를 오버라이딩하여 새로운 동작을 정의합니다.
class Animal {
public void makeSound() {
System.out.println("Some generic sound");
}
}
class Dog extends Animal {
// 오버라이딩
@Override
public void makeSound() {
System.out.println("Bark! Bark!");
}
// 자식 클래스의 추가 메서드
public void wagTail() {
System.out.println("Wagging tail");
}
}
public class OverridingExample {
public static void main(String[] args) {
Animal animal = new Animal();
animal.makeSound(); // Some generic sound
Dog dog = new Dog();
dog.makeSound(); // Bark! Bark!
dog.wagTail(); // Wagging tail
// 다형성을 이용하여 부모 클래스 타입으로 자식 클래스 객체 참조
Animal anotherDog = new Dog();
anotherDog.makeSound(); // Bark! Bark! (오버라이딩된 메서드가 호출됨)
}
}'JavaStudy' 카테고리의 다른 글
| [Java] 래퍼클래스(wrapper) (0) | 2023.12.05 |
|---|---|
| [Java] ArrayList (0) | 2023.12.04 |
| [Java] collections framework (1) | 2023.12.04 |
| [Java] 인터페이스(interface) (0) | 2023.12.02 |
| [Java] 예외처리(Exception Handling) (1) | 2023.12.01 |