본문 바로가기
대학강의정리/24.1 자바

chap6. 상속 연습문제

by 피스타0204 2024. 6. 6.

1. 다음 문장들의 T, F를 고르시오.

(1) 자식 클래스는 부모 클래스에서 물려받은 멤버 함수를 그대로 사용하거나 변경할 수 있고 새로운 멤버 변수나 함수를 추가 할 수 있다.

(2) 자식클래스는 보모 클래스보다 속성이나 동작이 더 적다.

(3) 부모 클래스를 상속한 자식 클래스는 부모 클래스와 has a관계이다.

(4) 상속은 코드 재사용성을 높인다.

더보기

1) T

2) F,         ,    수 있습니다.       더 많습니다. 

3) F, is a관계이다.

상속은 부모클래스와 자식클래스를 is-a 관계로 연결한 것입니다. has-a 관계와 착각하는 경우가 많지만 is-a 관계는 '원이 도형이다'처럼 공통적인 특징을 가졌기 때문에 자식 클래스가 부모 클래스에서 더 세분화됩니다. 반대로 has-a 관계는 '자동차는 엔진이 있다' 처럼 안에 클래스 안에 클래스가 있는 것이기 때문에 부모 클래스의 특징을 벗어나는 경우도 있습니다.

4) T

2. 자바에서 상속을 선언하는 방법은 무엇인가?

더보기

class 자식클래스 extends 부모클래스

3. 다음 코드가 틀린 이유를 적으시오.

class Ball extends Circle, Red{
    private String color;
    public Ball(String color){
        this.color = color;
    }
    public void findColor(){
        System.out.println(color+" 공이다.");
    }
    public void findVolume(){
        System.out.println("부피는 4/3*(π*반지름*반지름*반지름)이다.");
    }
}
더보기

자바는 다중상속을 지원하지 않는다. 

따라서 extends 뒤에 두 개 이상의 클래스가 올 수 없다.

4. 다음 Ball 클래스가 반지름과 넓이를 출력하도록 코드를 완성하시오. 상속을 사용해야 함.

class Circle{
    private void secret(){
        System.out.println("비밀이다.");
    }
    protected void findRadius(){
        System.out.println("반지름이 10.0센티이다.");
    }
    public void findArea(){
        System.out.println("넓이는 (π*반지름*반지름)이다.");
    }
}
class Ball{
    private String color;
    public Ball(String color){
        this.color = color;
    }
    public void findColor(){
        System.out.println(color+" 공이다.");
    }
    public void findVolume(){
        System.out.println("부피는 4/3*(π*반지름*반지름*반지름)이다.");
    }
}


public class Main
{
	public static void main(String[] args) {
	    Circle c1 = new Circle();
	    Ball c2 = new Ball("빨간색");
	    System.out.println("원 : ");
	    c1.findRadius();
	    c1.findArea();
	
		System.out.println("\n공:");
		c2.findColor();
	    c2.findVolume();
	    
	}
}
더보기
class Circle{
    private void secret(){
        System.out.println("비밀이다.");
    }
    protected void findRadius(){
        System.out.println("반지름이 10.0센티이다.");
    }
    public void findArea(){
        System.out.println("넓이는 (π*반지름*반지름)이다.");
    }
}
class Ball extends Circle{
    private String color;
    public Ball(String color){
        this.color = color;
    }
    public void findColor(){
        System.out.println(color+" 공이다.");
    }
    public void findVolume(){
        System.out.println("부피는 4/3*(π*반지름*반지름*반지름)이다.");
    }
}


public class Main
{
	public static void main(String[] args) {
	    Circle c1 = new Circle();
	    Ball c2 = new Ball("빨간색");
	    System.out.println("원 : ");
	    c1.findRadius();
	    c1.findArea();
	
		System.out.println("\n공:");
		c2.findRadius();
	    c2.findColor();
	    c2.findArea();
	    c2.findVolume();
	    
	}
}

5. 다음은 메서드 오버라이딩에 대한 설명이다.

(1) 부모 클래스로부터 물려받은 메서드를 자식클래스에서 수정하여 사용하는 것을 메서드 오버라이딩이라고 한다.

(2) 부모 클래스보다 자식 클래스의 접근 제어자를 더 좁게 변경할 수 있다.

(3) 부모 클래스보다 더 큰 범위의 예외를 선언할 수 없다.

(4) @Override는 자식 클래스의 오버라이딩한 메서드 앞에 쓰는 어노테이션이다. 부모 클래스의 멤버를 자식클래스에서 명시적으로 참조하려고 사용한다.

(5) final 메서드는 자식 클래스에 상속은 되지만 오버라이딩은 되지 않는다.

(6) 오버라이딩하는 메서드는 부모 클래스의 메서드와 동일한 시그니처를 사용하지만 반환타입은 달라도 된다.

더보기

1) T

2) F, 리스코프 치환법칙(LSP)에 따르면 부모 객체와 이를 상속한 자식 객체가 있을 때 부모 객체를 호출하는 동작에서 자식 객체가 부모 객체를 완전히 대체할 수 있어야 한다. 이는 객체지향 프로그래밍의 다형성 개념에서 업캐스팅하는 것에 대한 이야기인데, 만약 부모 클래스보다 자식 클래스의 접근 제어자를 더 좁게 변경하면, 업캐스팅이 불가능해진다. 이러한 복잡한 규칙에 의해 자바에서는 부모 클래스보다 자식 클래스의 접근 제어자를 더 좁게 변경하는 것이 금지되어 있다.
public> protected > default > private

3) T

4) T

5) T

6) F, 오버라이딩 규칙1, 부모 클래스의 메서드와 동일한 시그니처(매개변수, 이름)를 사용하고 반환 타입까지 동일해야 한다. 

6. 다음은 부모 클래스에 정의된 메소드들이다. 이 메소드 중 오버라이딩이 불가능한 메소드를 적고 그 이유를 적으시오.

class Pick{
    private void A(){
    }
    protected void B(){
    }
    public void C(){
    }
    public final void D(){}
    static void E(){}
}
더보기

A는 private메서드이기 때문에 자식 클래스에 상속되지 않는다. 부모 클래스가 전용으로 사용하기 때문에 오버라이딩 할 수 없다.

D는 final 메서드이기 때문에 수정이 불가능하다. 따라서 자식 클래스가 오버라이딩 할 수 없다.

E는 static 메서드이기 때문에 부모 클래스에만 소속된다. 자식 클래스에 상속되지 않음으로 오버라이딩 할 수 없다.

7. 다음 코드의 Ball클래스의 findArea() 를 오버라이딩하여 구의 넓이와 원의 넓이를 모두 출력하도록 만드시오.

package main;

class Circle {
	private void secret() {
		System.out.println("비밀이다.");
	}

	protected void findRadius() {
		System.out.println("반지름이 10.0센티이다.");
	}

	public void findArea() {
		System.out.println("넓이는 (π*반지름*반지름)이다.");
	}
}

class Ball extends Circle {
	private String color;

	public Ball(String color) {
		this.color = color;
	}

	public void findColor() {
		System.out.println(color + " 공이다.");
	}

	public void findVolume() {
		System.out.println("부피는 4/3*(π*반지름*반지름*반지름)이다.");
	}
}

public class Main {
	public static void main(String[] args) {
		Circle c1 = new Circle();
		Ball c2 = new Ball("빨간색");

		System.out.println("원 :");
		c1.findRadius();
		c1.findArea();

		System.out.println("\n공 :");
		c2.findRadius();
		c2.findColor();
		c2.findArea();
		c2.findVolume();
	}
}
더보기
package main;

class Circle {
	private void secret() {
		System.out.println("비밀이다.");
	}

	protected void findRadius() {
		System.out.println("반지름이 10.0센티이다.");
	}

	public void findArea() {
		System.out.println("면적은 (π*반지름*반지름)이다.");
	}
}

class Ball extends Circle {
	private String color;

	public Ball(String color) {
		this.color = color;
	}

	public void findColor() {
		System.out.println(color + " 공이다.");
	}
	
	@Override
	public void findArea() {
    	super.findArea();
		System.out.println("넓이는 4*(π*반지름*반지름)이다.");
	}

	public void findVolume() {
		System.out.println("부피는 4/3*(π*반지름*반지름*반지름)이다.");
	}
}

public class Main{
	public static void main(String[] args) {
		Circle c1 = new Circle();
		Ball c2 = new Ball("빨간색");

		System.out.println("원 :");
		c1.findRadius();
		c1.findArea();

		System.out.println("\n공 :");
		c2.findRadius();
		c2.findColor();
		c2.findArea();
		c2.findVolume();
	}
}

8. 다음은 super키워드에 대한 설명이다 T,F를 고르시오.

(1) super키워드는 자식 클래스에서만 사용할 수 있다.

(2) super키워드는 현재 객체에서 부모 클래스를 참조하는 것이다.

(3) 자식 클래스가 상속받은 메서드를 오버라이딩하면 자식 객체는 부모클래스의 원래 메서드를 숨긴다. 숨긴 메서드를 호출하는 데 super 키워드를 사용한다.

더보기

T

T

T

 

9. 다음 코드의 틀린 부분을 찾고 이유를 적으시오.

package main;

class Circle {
	private void secret() {
		System.out.println("비밀이다.");
	}

	protected void findRadius() {
		System.out.println("반지름이 10.0센티이다.");
	}

	public void findArea() {
		System.out.println("면적은 (π*반지름*반지름)이다.");
	}
}

class Ball extends Circle {
	private String color;

	public Ball(String color) {
		this.color = color;
	}

	public void findColor() {
		System.out.println(color + " 공이다.");
	}

	public void findArea() {
		findRadius();
		super.secret();

		System.out.println("넓이는 4*(π*반지름*반지름)이다.");
	}

	public void findVolume() {
		System.out.println("부피는 4/3*(π*반지름*반지름*반지름)이다.");
	}
}

public class Main{
	public static void main(String[] args) {
		Circle c1 = new Circle();
		Ball c2 = new Ball("빨간색");

		System.out.println("원 :");
		c1.findRadius();
		c1.findArea();

		System.out.println("\n공 :");
		c2.findRadius();
		c2.findColor();
		c2.findArea();
		c2.findVolume();
	}
}
더보기

super.secret();

private으로 정의된 부모 클래스의 메서드는 자식 클래스에 상속되지 않으므로 자식클래스에서 사요할 수 없다.

super사용하는 메서드는 부모 클래스에서 가져오는 것이 아니라 부모 클래스에서 상속으로 복사해온 메서드 이기 때문에 static, private은 사용할 수 없다.

secret메서드가 final로 정의되어 있다면 사용할 수 있다.

10. 메서드 오버라이딩과 메서드 오버로딩에 대해 비교하시오.

더보기

메서드 오버로딩은 상속과 완전히 상관이 없기 때문에 상속관계도 필요없고, 예외와 접근 범위에 대한 제약이 없습니다. 다형성의 개념도 아니기 때문에 호출할 메서드를 컴파일할 때 결정하는 정적 바인딩을 사용합니다.  메서드 이름은 원래 메서드와 동일해야 하지만 매개변수 이름이 달라야 합니다. 반환타입의 경우 같아도, 달라도 상관없습니다.

메서드 오버라이딩은 일단, 메서드이름, 매개변수이름, 반환 타입 모두 부모 클래스의 메서드와 같아야 하고, 상속관계가 꼭필요하며 예외와 접근범위에 제약이 있습니다. 다형성과도 밀접한 개념으로 호출할 메서드를 실행 중 결정하는 동적 바인딩을 사용합니다.

11. 다음은 패키지에 대한 설명이다. T,F를 구별하시오.

(1) 패키지는 클래스 파일을 묶어서 관리하기 위한 폴더이다.

(2) 자바에서는 .java 파일에 클래스를 저장한다.

(3) 패키지마다 별도의 이름공간(namespace)가 생기기 때문에 클래스의 유일성이 보장된다.

(4) 패키지1의 a와 패키지2의 a는 이름이 같으므로 같다.

(5) 클래스를 패키지 단위로 제어할 수 있으므로 패키지를 사용하면 접근을 더 세밀하게 제어할 수 있다.

(6) 패키지는 첫 행 외에도 선언할 수 있다.

(7) 단순히 컴파일하면 패키지 폴더가 생성되지 않지만 패키지 선언을 포함하는 자바 소스 코드를 컴파일하면 패키지 이름(패키지 경로)에 대응하는 폴더가 생성된다.

더보기

1) T

2) T

3) T

4) F, 패키지마자 별도의 이름 공간(namespace)이 생기기 때문에 클래스 이름의 유일성을 보장합니다. 패키지 1의 클래스a와 패키지 2의 클래스a를 다른 클래스로 취급해줍니다.

5) T

6) F, 패키지는 반드시 첫 행에 선언해야 한다.

7) T

12. 다음 코드는 기본 패키지가 아니라 사용자가 작성한 자바 코드이다. 컴파일 에러가 난 이유를 적으시오.

public class Main{
	public static void main(String[] args) {
		System.out.println("와우");
	}
}
더보기

기본 패키지가 아닐때는 파일 위에 패키지 선언을 해주어야 합니다. 지금까지는 package main;을 사용했습니다.

package main;
public class Main{
	public static void main(String[] args) {
		System.out.println("와우");
	}
}

13. 지금까지 패키지를 선언하는 방법을 알아봤다. 패키지를 사용하는 두 가지 방법에 대해 설명하시오.

더보기

클래스 경로와 함께 사용하는 방법과 import해서 사용하는 방법이 있다.

클래스 경로를 바로 사용하는 방법은 다음과 같이 패키지 이름을 접두어로 사용해  현재 패키지가 아닌 다른 패키지의 클래스를 사용할 수 있다.

import문을 사용해 클래스가 아닌 메소드를 불러올 수 있다.

14. java.util 패키지에 있는 Arrays클래스에서 sort를 import해 다음 코드를 정렬하시오.

public class Main{

    public static void main(String[] args) {
        int[] intArr = {5,3,2,1,4};
        for (int i : intArr) 
            System.out.print(i + " ");
        System.out.println();
		
    }
}
더보기
import java.util.Arrays.sort;
public class Main{

    public static void main(String[] args) {
        int[] intArr = {5,3,2,1,4};
        sort(intArr);
        for (int i : intArr) 
            System.out.print(i + " ");
        System.out.println();
		
    }
}

15. 자식 생성자와 부모 생성자에 대한 설명이다. T,F를 고르시오.

(1) 생성자는 자식 클래스에 상속된다.

(2) 부모에게서 물려받은 멤버가 있다면 자식 클래스는 이를 초기화하기 위해 인스턴스를 생성할 때 부모 생성자를 호출한다.

(3) 자식 클래스의 인스턴스를 생성하면 부모 생성자가 먼저 호출되고 자식 생성자가 호출된다.

(4) 컴파일러가 부모 생성자를 암시적으로 호출할 때, 부모 생성자에 인수있는 생성자만 명시되어 있다면 오류가 발생한다. 

(5) 부모 생성자를 자식 클래스에서 호출하기 위해 super();나 super(매개변수);가 사용된다.

더보기

1) F, 생성자는 클래스 멤버가 아니므로 자식 클래스에 상속되지 않는다.

2) T

3) T

4) T

5) T

16. 다음 코드가 틀렸다면 틀린 이유를 설명하고 고치시오.

package main;

class Box{
	public Box(String s) {
		System.out.println("Box constructor");
	}
}

class ColoredBox extends Box {
	public ColoredBox() {
		System.out.println("ColoredBox constructor");
	}
}

public class Main {
	public static void main(String[] args) {
		ColoredBox rdBox = new ColoredBox();
	}
}
더보기

틀렸다. 

컴파일러는 자식클래스인 ColoredBox의 인스턴스를 만들 때, 부모 클래스인 Box 인수 없는 생성자를 암시적으로 불러오려고 한다. 하지만 부모 클래스에 인수 있는 생성자가 명시되어 있고, 인수 없는 생성자가 명시되어 있지 않으므로 부모 클래스에는 인수없는 생성자가 암시적으로도 생성되지 않는다. 그렇기 때문에 super();로 부모 생성자를 암시적으로 불러올 수 없게 되어 오류가 발생한다.

package main;

class Box{
	public Box() {
		System.out.println("Box constructor");
	}
}

class ColoredBox extends Box {
	public ColoredBox() {
		System.out.println("ColoredBox constructor");
	}
}

public class Main {
	public static void main(String[] args) {
		ColoredBox rdBox = new ColoredBox();
	}
}

로 바꾸어야 한다.

17. 다음 코드가 틀렸다면 틀린 이유를 설명하고 고치시오.

package main;

class Box{
}

class ColoredBox extends Box {
	public ColoredBox(String s) {
    	super(s);
		System.out.println("ColoredBox constructor");
	}
}

public class Main {
	public static void main(String[] args) {
		ColoredBox rdBox = new ColoredBox();
	}
}
더보기
틀렸다.
부모 생성자에 인수 있는 생성자가 없다.
package main;

class Box{
}

class ColoredBox extends Box {
	public ColoredBox(String s) {
    	super(); //없어도 됨.
		System.out.println("ColoredBox constructor");
	}
}

public class Main {
	public static void main(String[] args) {
		ColoredBox rdBox = new ColoredBox();
	}
}
로 바꾸어야 한다.

18. 다음 코드가 틀렸다면 틀린 이유를 설명하고 고치시오.

package main;

class Animal {
	public Animal(String s) {
		System.out.println("동물 : " + s);
	}
}

class Mammal extends Animal {
	public Mammal() {
		super();
		System.out.println("포유류 : 원숭이");
	}

	public Mammal(String s) {
		super(s);
		System.out.println("포유류 : " + s);
	}
}

public class Main {
	public static void main(String[] args) {
		Mammal ape = new Mammal();
		Mammal lion = new Mammal("사자");
	}
}
더보기
package main;

class Animal {
	public Animal(String s) {
		System.out.println("동물 : " + s);
	}
}

class Mammal extends Animal {
	public Mammal() {
		// super(); //오류
		super("원숭이");
		System.out.println("포유류 : 원숭이");
	}

	public Mammal(String s) {
		super(s);
		System.out.println("포유류 : " + s);
	}
}

public class Main {
	public static void main(String[] args) {
		Mammal ape = new Mammal();
		Mammal lion = new Mammal("사자");
	}
}

로 바꾸어야 한다.

19. 다음은 접근자와 final 클래스에 대한 설명이다.  T, F를 고르시오.

(1) public접근 제어자로 멤버를 선언하면 어떤 클래스에서 접근하든 해당 멤버에 접근할 수 있다.

(2) protected 접근 제어자로 선언된 멤버는 해당 클래스와 해당 클래스를 상속받은 외부 패키지의 클래스에서만 접근할 수 있다.

(3) default 접근 제어자는 package-private이라고 불리고 같은 패키지 내의 클래스들만 접근할 수 있는 제어자이다. 

(4) 접근 제어자를 명시하지 않으면 같은 패키지 내의 클래스들에서만 접근할 수 있다.

(5) private은 오직 같은 클래스 내에서만 접근할 수 있는 접근자이다.

(6) final 멤버처럼 private멤버는 자식 클래스에 상속된다.

(7) 클래스 멤버는 어떤 접근 지정자로도 지정할 수 있지만 클래스는 모든 접근제어자 중 유일하게 protected로는 지정할 수 없다.

(8) final 클래스는 더이상 상속할 수 없는 종단 클래스를 말하고 클래스 내부의 모든 메서드의 오버라이딩을 막는데 사용한다.

(9) final 메서드는 특정 메서드만 오버라이딩 하지 않게 할 때 사용한다.

(10) 자식 클래스는 부모 클래스의 public멤버와 protected멤버를 상속받는다.

(11) import문은 다른 패키지에 있는 공개된 클래스의 패키지 경로를 컴파일러에게 알려준다.

더보기

1) T

2) F, protected 접근 제어자로 선언된 멤버는 "같은 패키지 내의 클래스"와 해당 클래스를 상속받은 외부 패키지의 클래스에서만 접근할 수 있다.

3) T 

4) T

5) T

6) F, final메서드는 자식 클래스에 상속되지만 private멤버는 자식 클래스에 상속되지 않는다.

7) F, 클래스 멤버는 어떤 접근 지정자로도 지정할 수 있지만 클래스는 protected와 private으로 지정할 수 없다.

8) T

9) T

10) T

11) T

20. 다음 빈칸을 채우시오.

21. 다음 코드에서 틀린 것을 모두 고치시오.

package sec06;
public class One {
	private int secret = 1;
    int roomate = 2;
    protected int child = 3;
    public int anybody = 4;
    public void show(){}
}

public class One1 extends One{
	void print(){
    System.out.println(secret);
    System.out.println(roomate);
    System.out.println(child);
    System.out.println(anybody);
	}
    void show(){}
}
더보기
package sec06;
public class One {
	private int secret = 1;
    int roomate = 2;
    protected int child = 3;
    public int anybody = 4;
    public void show(){}
}

public class One1 extends One{
	void print(){
    //System.out.println(secret);
    System.out.println(roomate);
    System.out.println(child);
    System.out.println(anybody);
	}
    //void show(){}
}

private멤버는 외부 클래스에서 접근할 수 없고(자식 클래스라 하더라도), 오버라이딩을 할 때는 접근 범위가 줄어들면 안되기 때문에 show를 default로 설정할 수 없다. 반드시 public으로 설정해주어야 한다.

22. 다음 코드에서 올바르게 작동하는 statement를 고르시오.

package sec06;
public class One {
	private int secret = 1;
    int roomate = 2;
    protected int child = 3;
    public int anybody = 4;
    private void show(){}
}
-----------------다른 파일
package sec06.other;
import sec06.One;
public class Three{
	void print(){
    One o = new One();
    System.out.println(o.secret); //1
    System.out.println(o.roomate); //2
    System.out.println(o.child); //3
    System.out.println(o.anybody);  //4
	}
    o.show(); //5
}
더보기

4,

1,5는 private이므로 다른 클래스인 Three에서는 접근할 수없다.

2 는 default이기 때문에 다른 패키지에서 접근할 수 없다.

3은 자식 클래스와 자기자신만 접근할 수 있기 때문에 접근할 수 없다.

 

22. 다음 코드가 틀린 이유를 말하고 고치시오.

package main;

class Good {
}

class Better extends Good {
}

final class Best extends Better {
}
class NumberOne extends Best {}

public class Main {
	public static void main(String[] args) {
		
		new Best();
		new NumberOne();
	}
}
더보기

상속할 수 있고 오버라이딩 할 수 없는 final멤버와 다르게 final 클래스는 상속할 수 없는 종단 클래스이다.

package main;

class Good {
}

class Better extends Good {
}

final class Best extends Better {
}
//class NumberOne extends Best {}

public class Main {
	public static void main(String[] args) {
		
		new Best();
		//new NumberOne(); //오류
	}
}

로 바꾸어야 한다.

23. 다음 코드가 틀린 이유를 말하고 고치시오.

package main;

class Chess {
	enum ChessPlayer {
		WHITE, BLACK
	}

	final ChessPlayer getFirstPlayer() {
		return ChessPlayer.WHITE;
	}
}

class WorldChess extends Chess {
	ChessPlayer getFirstPlayer() {}
}

public class Main {
	public static void main(String[] args) {
		WorldChess w = new WorldChess();
		w.getFirstPlayer();
		System.out.println(Chess.ChessPlayer.WHITE);
	}
}
더보기

final 메서드는 오버라이딩이 불가능하다.

package main;

class Chess {
	enum ChessPlayer {
		WHITE, BLACK
	}

	final ChessPlayer getFirstPlayer() {
		return ChessPlayer.WHITE;
	}
}

class WorldChess extends Chess {
//	ChessPlayer getFirstPlayer() {}
}

public class Main {
	public static void main(String[] args) {
		WorldChess w = new WorldChess();
		w.getFirstPlayer();
		System.out.println(Chess.ChessPlayer.WHITE);
	}
}

다음과 같이 바꾸어야 한다.

24. 다음은 다형성과 타입변환에 대한 설명이다. T,F를 고르시오.

(1) 부모클래스를 자식클래스로 타입 변환할 수 있다.

(2) 부모 타입으로 형변환하면 부모 타입에 있는 멤버만 사용할 수 있다.

(3) 다형성은 객체의 타입에 따라 메서드를 다르게 동작하도록 구현하는 것이다.

(4) string 클래스는 final클래스로 자식 클래스를 정의하면 오류가 발생한다.

(5) instanceof연산자는 변수가 참조하는 실제 객체의 타입을 식별하는 연산자이다.

더보기

1) F, 자식 클래스는 부모의 모든 클래스를 포함하고 있기 때문에 자식 클래스를 부모 클래스로 타입 변환할 수 있습니다. 반대는 안됩니다.

2) T

3) T

4) T

 

25. 다음 코드에서 틀린 부분을 찾고 고치시오.

public class Person{
	String name = "사람";
    void whoami(){
    	System.out.println("나는 사람이다.");
        {
    }
}
public class Student extends Person{
	int number =7;
    void work(){
    	System.out.println("나는 공부한다.");
    }
}
public class Main{
	public static void main(String[] args){
    	Student s = new Student();
        Person p = s;
        p.number = 1;
        p.work();
        p.whoami();
    }
}
더보기
public class Person{
	String name = "사람";
    void whoami(){
    	System.out.println("나는 사람이다.");
        {
    }
}
public class Student extends Person{
	int number =7;
    void work(){
    	System.out.println("나는 공부한다.");
    }
}
public class Main{
	public static void main(String[] args){
    	Student s = new Student();
        Person p = s;
        p.whoami();
    }
}

Person p =s;를 하면 p = (Person)s;와 같다.

p는 Person타입이기 때문에 student타입에만 있는 number와 work() 멤버는 사용할 수 없다.

부모 타입으로 형변환하면 부모 타입에 있는 멤버만 사용할 수 있다.

26. 다음은 p변수를 자식 클래스인 Student로 형변환하려고 하는 코드이다. 옳게 고치시오.

Person p = new Person();
Student s = (Student) p;
더보기
Student s1 = new Student();
Person p = s1;
Student s2= (Student) p;

부모 객체에 자식 객체를 대입해 부모 객체의 메소드 바운더리를 자식 객체만큼 넓혀주면 강제 타입변환이 가능해진다. 사실상 s2 = s1이 되기 때문에 가능하다.

즉, 자식 객체였던 부모 객체만 자식 객체로 형변환이 가능하다.

27. 다음 코드의 출력을 적으시오.

class Person{
	String name = "사람";
    void whoami(){
    	System.out.println("나는 사람이다.");
    }
}
class Student extends Person{
	int number =7;
    void work(){
    	System.out.println("나는 공부한다.");
    }
}
public class Main{
	public static void main(String[] args){
    	Student s = new Student();
        Person p = new Person();
        System.out.println(s instanceof Person);
        System.out.println(s instanceof Student);
        System.out.println(p instanceof Person);   
        System.out.println(p instanceof Student);  
    }
}
더보기

true
true
true
false

28. 상속을 설명한 것이다. 틀린 것은?

  1. 모든 클래스의 최상위 클래스는 Object이다.
  2. 부모 객체를 자식 클래스 타입의 변수에 대입할 수 있다.
  3. 부모 클래스의 private 메서드를 자식 클래스가 오버 라이딩할 수 없다.
  4. 부모 클래스를 상속하려면 extends 키워드가 필요하다.
더보기

2, 부모 객체는 자식 클래스 타입의 변수에 대입할 수 없다. 가 정석이다.

29. 다음 코드의 밑줄 친 부분에 적절치 않은 코드는?

class Car {
    public String name;
    protected String color;
    private int model;
}

class SportsCar extends Car {
    boolean turbo;
}

public class CarTest {
    public static void main(String[] args) {
        SportsCar s = new SportsCar();
        -------------------------
    }
}
  1. s.name = "ferrari";
  2. s.color = "red";
  3. s.model = 105;
  4. s.turbo = true;
더보기

3, model은 private접근 제어자로 설정되어 있다.

30. 다음 코드의 실행결과는? 만약 오류가 발생한다면 그 이유를 이야기하시오.

class Apple { }
class Fox { }
public class Test {
    public static void main(String[] args) {
        Apple a = new Apple();
        System.out.println(a instanceof Fox);
    }
}
더보기

오류가 발생한다. 변수가 해당타입과 완전히 관련이 없을 경우, instanceof연산자는 오류를 발생시킨다.

31.접근 제어를 설명한 것이다. 옳은 것은?

  1. private < package < protected < public
  2. private < protected < package < public
  3. package < private < protected < public
  4. package < protected < private < public
더보기

1, private는 동일한 클래스만, default는 동일한 클래스 + 동일한 패키지에서 protected는 동일한 클래스, 동일한 패키지, 자손 클래스까지 public은 접근 제한이 전혀 없다.

32. 다음 코드에서 오류가 발생한다. 그 이유는?

class Fruit {
    String color;

    public Fruit(String color) {
        this.color = color;
    }
}

public class Apple extends Fruit{
    double weight;
    
    public Apple(double weight) {
        this.weight = weight;
    }
}
더보기

Fruit 클래스에 인수없는 생성자가 없어서 발생한다.

33.다음과 같은 부모 클래스와 자식 클래스가 있다. 질문에 답하시오.

 

class Person {
    void name() { }
    protected void number() { }
    void weight() { }
    static void show() { }
    private void secret() { }
}

class Student extends Person {
    public void name() { }
    void number() { }
    static void weight() { }
    static void show() { }
    private void secret() { }
}
  1. Student 클래스의 메서드 중 오류가 발생하는 메서드를 나열하고 원인을 적는다.
  2. Person 클래스의 메서드 중 Student 클래스가 오버 라이딩한 메서드를 나열한다.
더보기

1. number() : 접근제어자 범위가 작아지면 안된다.

weight() : 자식 클래스의 정적 메서드는 부모 클래스의 인스턴스 메서드를 재정의할 수 없다.

 

2. name()

number()과  weight()은 오류 메서드이고

show, secret는 오버라이딩 될 수 없는 메서드이다.

show()는 부모 클래스에 종속되어 있는 정적 메서드이고, secret()은 private으로 정의되어 자식 클래스에서도 접근이 불가능하다.