Person 클래스가 있고 그를 상속 받는 Giwoong 클래스가 있습니다.
이 때 두 클래스가 가지고 있는 메서드는 다음과 같습니다.
Person: eat(), sleep()
Giwoong: eat(), study()
여기서 Person 인스턴스 = new Giwoong();의 형태로 인스턴스를 생성하면 해당 인스턴스는 study() 메서드를 사용할 수 없다.
이용할 수 없는 이유와 해당 인스턴스로 study() 메서드를 이용하기 위해 추가할 수 있는 코드는?
(코드로 구현)
public class Person {
void eat() {
System.out.println("사람은 음식을 먹습니다.");
}
void sleep() {
System.out.println("사람은 잠을 잡니다.");
}
}
class Giwoong extends Person{
@Override
void eat() {
System.out.println("기웅님은 음식을 먹습니다.");
}
void study() {
System.out.println("기웅님은 공부합니다.");
}
}
public class Main {
public static void main(String[] args) {
Person person1 = new Giwoong();
person1.study(); //컴파일 에러
}
}
다음 코드를 실행할 때 실행 결과는 무엇일까요?
class A {
public void method() {
System.out.println("A.method");
}
}
class B extends A {
public void method() {
System.out.println("B.method");
super.method();
}
}
class C extends B {
public void method() {
System.out.println("C.method");
super.method();
}
}
public class Main {
public static void main(String[] args) {
A a = new C();
a.method();
}
}
자바에서 상속된 메서드를 오버라이드할 때, @Override 어노테이션을 사용하는 이유는 무엇인가요?
자식 클래스에서 부모 클래스의 protected 메서드를 호출할 수 있는 이유는 무엇인가요?
부모 클래스에 “method”란 이름의 메서드가 있습니다. 자식 클래스에서는 “method”라는 이름의 메서드를 사용하지만 매개변수는 부모의 메서드와 다르게 받습니다. 이건 오버라이딩이라고 받아들여질까요?
public class Parent {
int a = 10;
int b = 20;
public void printAB() {
System.out.println(a);
System.out.println(b);
}
}
public class Child extends Parent {
int a = 30;
int b = 40;
@Override
public void printAB() {
// 여기에 들어갈 코드를 완성해주세요.
}
}
public class Parent {
int a = 10;
int b = 20;
public void printAB() {
System.out.println(a);
System.out.println(b);
}
}
public class Child extends Parent {
int a = 30;
int b = 40;
@Override
public void printAB() {
super.printAB// 여기에 들어갈 코드를 완성해주세요.
}
}
(protected 포함) 접근제어자