Skip to content
This repository was archived by the owner on Aug 17, 2025. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
6b2f847
docs: README
OmaryKoo Jun 9, 2025
066e6ab
feat: Cleric class / test code for 퀴즈1
OmaryKoo Jun 10, 2025
b980911
feat: Cleric class / test code for 퀴즈1(다시)
OmaryKoo Jun 10, 2025
2337037
feat: Cleric class / test code for 퀴즈2
OmaryKoo Jun 10, 2025
91aa9b8
feat: pray() 추가_퀴즈3
OmaryKoo Jun 10, 2025
c4d0b5b
feat: selfAid() 수정
OmaryKoo Jun 10, 2025
1d6d57d
feat: 25.06.10 수업내용정리
OmaryKoo Jun 10, 2025
d7f6f9f
feat:
OmaryKoo Jun 10, 2025
c290b79
feat:다시연습1
OmaryKoo Jun 13, 2025
bf2fbde
feat:다시연습2
OmaryKoo Jun 13, 2025
f8b2a7c
feat:다시연습3
OmaryKoo Jun 15, 2025
663118d
feat: test
Jun 16, 2025
cc30da9
feat: Q1. Cleric static 테스트
Jun 16, 2025
bf44c0e
feat: Q2. Cleric 생성자 테스트
Jun 16, 2025
f9fdaa3
feat: 용어정리
Jun 16, 2025
3bb76c8
feat: 모든 필드와 메소드 접근지정자 private 추가 및 getter/setter 작성 (연습문제1-1)
Jun 17, 2025
d555d4f
feat: 인수의 타당성 검사 throw new IllegalArgumentException() (연습문제1-2)
Jun 17, 2025
bfce20c
feat: Date클래스 (연습문제2)
Jun 17, 2025
d887d2a
feat: Slime 상속 및 속성 테스트
OmaryKoo Jun 23, 2025
ff949ea
feat: wizard 속성 수정 (연습문제4)
OmaryKoo Jun 23, 2025
655a336
feat: greatWizard 클래스 요구사항 + 상속(연습문제5)
OmaryKoo Jun 23, 2025
09b0f41
feat: TangibleAsset 추상클래스 정의 및 Book/Computer 상속 구조 구현 (연습문제1)
OmaryKoo Jun 24, 2025
141fd5f
feat: Asset 추상클래스 정의 및 하위 상속 구조 구현 수정 (연습문제2)
OmaryKoo Jun 24, 2025
2419a07
feat: interface Thing정의와 상위 클래스에서 implements (연습문제3)
OmaryKoo Jun 24, 2025
c0280d9
feat: 용어정리
OmaryKoo Jun 24, 2025
acaa5f3
feat: 제네릭을 사용한 클래스 (연습문제4-1)
OmaryKoo Jul 1, 2025
92edd51
feat: Enum 열거형 타입을 사용한 클래스 limit 적용 (연습문제4-2)
OmaryKoo Jul 1, 2025
f53e54b
feat: Book2 함수 / Book2Test 작성
OmaryKoo Jul 7, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions TIL/topics/java_basic/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# 저는 구태한입니다.
144 changes: 144 additions & 0 deletions TIL/topics/java_basic/용어정리.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@

# 인스턴스의 기본 조작 (25.07.07)
### equals() & hashCode()
* equals(): 객체의 내용 비교를 위한 메서드
* hashCode(): 객체를 해서 기반 컬렉션(Set,Map 등)에 넣기 위한 해시값 생성기

### toString() & clone()
* toString(): 객체의 내용을 문자열로 확인할 때 유용
* clone(): 객체 복사 지원(Cloneable 인터페이스와 함께 사용)

### 얕은 복사 & 깊은 복사
* 얕은 복사: 참조 변수 주소만 복사 / 내부 객체는 같은 인스턴스 공유
* 깊은 복사: 내부 객체까지 새로 복사 / 내부 객체도 새로운 인스턴스


# 제네릭, 열거형, 중첩 클래스 (25.07.01)
### 제네릭(Generic)
* 타입을 일반화해서 작성 -> 나중에 구체적인 타입 지정
* T, E, K, V 일반적으로 표현하나 자유롭게~

### 열거형(Enum)
* 상수들을 하나의 타입으로 묶음
* 내부에 필드와 생성자도 가질 수 있음(사실상 객체)

```java
enum KeyType {
PADLOCK(1024), BUTTON(10000);
private final int limit;
KeyType(int limit) {
this.limit = limit;
}
public int getLimit() {
return limit;
}
}
```


# 추상클래스와 인터페이스 (25.06.24)
* 클래스는 크게 **일반 클래스**와 **추상 클래스**로 나뉨. **추상 클래스**는 클래스 내 '추상 클래스'가 하나이상 포함하거나
abstract로 정의된 경우를 말함.
* **인터페이스**는 모든 메소드가 추상 메소드인 경우

### 추상클래스와 인터페이스의 차이점
추상클래스는 일부 구현된 설계도, 인터페이스는 기능 약속을 위한 설계도

*추상클래스* -> "is-a"관계 (Dog is an Animal -> Dog extends Animal)

*인터페이스* -> "can-do"관계 (Bird can Fly -> Bird implements Flyable)

### 메모
* protected는 자식 클래스에서는 접근이 쉽지만,
외부(예: 테스트 코드)에서는 직접 접근이 불가능하다.
따라서 외부 접근을 고려한다면, private으로 필드를 감추고
public getter/setter를 제공하는 방식이 더 명확하고 덜 혼란스럽다.



### 참고
[자바추상클래스](https://m.blog.naver.com/minsuuuus/222228495226)

[오버라이딩(Overriding)과 오버로딩(Overloading)](https://yeoonjae.tistory.com/entry/JAVA-%EC%98%A4%EB%B2%84%EB%9D%BC%EC%9D%B4%EB%94%A9Overriding%EA%B3%BC-%EC%98%A4%EB%B2%84%EB%A1%9C%EB%94%A9Overloading%EC%9D%98-%EC%B0%A8%EC%9D%B4%EC%A0%90)

---
# 상속 용어 정리 (25.06.23)

* 상속(Inheritance)은 부모가 자식에게 물려주는 행위를 말한다. OOP에서도 부모 클래스의 필드&메서드를 자식 클래스에게 물려줄 수 있음.
* public class PoisonSlime extends Slime {

}
위와 같이 부모 클래스를 extends 뒤에 기술함.
프로그램에서는 자식이 부모를 선택함.

▶ 자바에서는 다중 상속을 허용하지 않음!! 여러 개 부모 클래스를 상속할 수 없음. 따라서 extends 뒤에는 단 하나의 부모 클래스만이 와야 함.

* super = 부모 클래스에 접근하는 키워드
상속구조에서, 자식 클래스는 부모 클래스의 속성과 매서드를 상속받아 사용할 수 있는데, super를 쓰면 부모의 기능을 호출하거나 접근가능.

▶ this. 나 자신
▶ super. 부모

* 오버라이딩 : 부모 클래스에서 정의한 매서드를 자식 클래스에서 재정의
부모의 것을 그대로 쓰는 게 아니라 입맛대로 바꿔서 쓰겠다? 그런 의미

@Override
public void attack(Hero hero) {
super.attack(hero);
~
}

@Override는 부모에 정의된 매서드를 재정의하고 있다는 표시

---
# 캡슐화 용어 정리 (25.06.17)

* 캡슐화란,
캡슐화는 클래스 내부의 데이터에 외부에서 직접 접근하지 못하도록 막고, 대신 메서드를 통해서만 접근하게 하여
데이터를 안전하게 보호하는 개념. 특히 현실 세계에서는 들어갈 수 없는 잘못된 값이 필드에 저장되지 않도록 제어하는 데 매우 중요

* 접근 제한자에 따른 멤버 접근 규칙
private으로 선언된 필드는 해당 클래스 내부에서만 접근 가능
public으로 선언된 필드나 메서드는 어떤 클래스에서도 자유롭게 접근 가능

* 캡슐화를 올바르게 적용하려면, 클래스는 public으로 선언하고, 필드는 반드시 private로 선언.
필드에 접근하고 수정하기 위해서는 public 매서드(getter,setter)를 따로 만들어 제공함.


##클래스 생성자 용어 정리 (25.06.16)

* 클래스 변수는 값이 아니라 객체의 주소(참조)를 저장함.
그래서 하나의 객체를 여러 변수가 가리킬 수 있으며, 한 쪽에서 바꾸면 다른 쪽도 바뀜.


* 생성자는 객체를 만들 때 자동으로 실행되는 메서드. 여러 개 만들 수 있음(오버로딩), 그리고 this로 다른 생성자를 내부에서 부를 수도 있음.


* 정적 멤버(static)이 붙은 변수나 메서드는 클래스명, 변수명으로 바로 쓸 수 있고, 모든 인스턴스가 같은 값을 공유함.

---
# 객체지향언어 용어 정리 (25.06.10)

오브젝트(object) : 현실 세계 모든 객체(사물이 아닌 경우가 많음)

클래스(class) : 객체를 만들어내기 위한 설계도 / 변수와 매서드의 집합

인스턴스(instance) : 설계도를 바탕으로 가상 세계에 구현된 구체적인 실체(실체화된 인스턴스는 메모리에 할당)

*직무에선 오브젝트를 인스턴스와 같은 개념으로 혼용하며 사용된다함.

클래스를 만드는 이유는 재사용성 때문에 만듦.



final : 변경불가 키워드(const 같은 거) _ 한번 초기화되면 이후로 값이 바뀔 수 없음.
this : 현재 객체를 참조하는 키워드 _ 현재 객체 자기 자신을 가리킴.


## 메모
객체마다 고유의 속성이 있는데, class로 표현하면 이해하기가 수월함.
객체지향을 함으로써 성능면에서는 메리트가 없음(메모리 사용 or 실행 속도 등)

비록 느리고 메모리 사용도 많은 객체지향 방식을 굳이 쓰는 이유가 개발자가 헷갈리지 않게 하려고, 결국 버그를 줄이기 위함.


2 changes: 2 additions & 0 deletions src/main/java/com/survivalcoding/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
public class Main {
public static void main(String[] args) {


System.out.print("Hello and welcome!");

for (int i = 1; i <= 5; i++) {
Expand Down
31 changes: 31 additions & 0 deletions src/main/java/com/survivalcoding/TangibleAsset.puml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
@startuml
'https://plantuml.com/class-diagram

interface Thing {
+double weight()
}
Comment on lines +4 to +6
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Thing 인터페이스 메서드명이 실제 구현과 불일치

UML 다이어그램에서는 weight() 메서드로 정의되어 있지만, 실제 Java 코드에서는 getWeight()setWeight(double weight) 메서드로 구현되어 있습니다.

 interface Thing {
-+double weight()
++double getWeight()
++void setWeight(double weight)
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
interface Thing {
+double weight()
}
interface Thing {
+double getWeight()
+void setWeight(double weight)
}
🤖 Prompt for AI Agents
In src/main/java/com/survivalcoding/TangibleAsset.puml around lines 4 to 6, the
Thing interface method name weight() does not match the actual Java
implementation which uses getWeight() and setWeight(double weight). Update the
UML diagram to replace weight() with getWeight() and setWeight(double weight)
methods to accurately reflect the Java code.


abstract class Asset {
-String name;
-int price;
}

class TangibleAsset extends Asset implements Thing {
-String color;
}
Comment on lines +13 to +15
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

TangibleAsset 클래스에 weight 필드 누락

실제 Java 코드에서는 weight 필드가 있지만 UML 다이어그램에는 누락되어 있습니다.

 class TangibleAsset extends Asset implements Thing {
 -String color;
+-double weight;
 }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/main/java/com/survivalcoding/TangibleAsset.puml around lines 13 to 15,
the UML class diagram for TangibleAsset is missing the weight field that exists
in the actual Java code. Add a weight attribute to the TangibleAsset class in
the UML diagram to accurately reflect the class structure.


class IntangibleAsset extends Asset {
}

class Book extends TangibleAsset {
-String isbn;
}

class Computer extends TangibleAsset {
-String makerName;
}

class Patent extends IntangibleAsset {
}

@enduml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.survivalcoding.assignments_01_instance.exam01;

//(가): Asset
public class Asset {
private String name;
private int price;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getPrice() {
return price;
}

public void setPrice(int price) {
this.price = price;
}

public Asset(String name, int price) {
this.name = name;
this.price = price;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.survivalcoding.assignments_01_instance.exam01;

public class Book extends TangibleAsset {
private String isbn;
private double weight;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

중복된 weight 필드 제거 권장

TangibleAsset 클래스가 이미 Thing 인터페이스를 통해 weight 기능을 제공하는 것으로 보입니다. 여기서 weight 필드를 중복 선언하면 혼란을 야기할 수 있습니다.

중복된 weight 필드를 제거하세요:

public class Book extends TangibleAsset {
    private String isbn;
-    private double weight;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private double weight;
public class Book extends TangibleAsset {
private String isbn;
🤖 Prompt for AI Agents
In src/main/java/com/survivalcoding/assignments_01_instance/exam01/Book.java at
line 5, remove the duplicate private double weight field since the TangibleAsset
class already provides weight functionality through the Thing interface. This
will prevent confusion and redundancy in the code.


public String getIsbn() {
return isbn;
}

public void setIsbn(String isbn) {
this.isbn = isbn;
}

public Book(String name, int price, String color, String isbn) {
super(name, price, color);
this.isbn = isbn;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package com.survivalcoding.assignments_01_instance.exam01;

import java.util.Date;

public class Book2 implements Comparable<Book2> {
private String title;
private Date publishDate;
private String comment;

public Book2(String title, Date publishDate, String comment) {
this.title = title;
this.publishDate = publishDate;
this.comment = comment;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public Date getPublishDate() {
return publishDate;
}
Comment on lines +24 to +26
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Date 객체의 가변성으로 인한 캡슐화 위반 가능성

Date 객체는 가변 객체이므로 getter에서 직접 반환하면 외부에서 내부 상태를 변경할 수 있습니다.

방어적 복사를 통해 캡슐화를 보장하세요:

public Date getPublishDate() {
-   return publishDate;
+   return publishDate != null ? (Date) publishDate.clone() : null;
}
🤖 Prompt for AI Agents
In src/main/java/com/survivalcoding/assignments_01_instance/exam01/Book2.java
around lines 24 to 26, the getPublishDate method returns the mutable Date object
directly, which can lead to encapsulation violation by allowing external
modification of the internal state. To fix this, modify the getter to return a
defensive copy of the publishDate by creating and returning a new Date object
initialized with the value of publishDate, thus preserving encapsulation.


public void setPublishDate(Date publishDate) {
this.publishDate = publishDate;
}
Comment on lines +28 to +30
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Date 객체의 가변성으로 인한 캡슐화 위반 가능성

외부에서 전달된 Date 객체를 직접 할당하면 외부에서 내부 상태를 변경할 수 있습니다.

방어적 복사를 통해 캡슐화를 보장하세요:

public void setPublishDate(Date publishDate) {
-   this.publishDate = publishDate;
+   this.publishDate = publishDate != null ? (Date) publishDate.clone() : null;
}
🤖 Prompt for AI Agents
In src/main/java/com/survivalcoding/assignments_01_instance/exam01/Book2.java
around lines 28 to 30, the setter method for publishDate directly assigns the
passed Date object, which can lead to encapsulation violation due to Date's
mutability. Fix this by creating a defensive copy of the passed Date object
before assigning it to the field, ensuring internal state cannot be altered
externally.


public String getComment() {
return comment;
}

public void setComment(String comment) {
this.comment = comment;
}

@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;

Book2 other = (Book2) obj;
return this.title.equals(other.title) && this.publishDate.equals(other.publishDate);
}
Comment on lines +41 to +47
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

equals 메서드에서 null 포인터 예외 위험이 있습니다.

title이 null인 경우 46번 라인에서 NullPointerException이 발생할 수 있습니다. 방어적 프로그래밍을 위해 null 체크를 추가해야 합니다.

다음과 같이 수정하여 null 안전성을 보장하세요:

@Override
public boolean equals(Object obj) {
    if (this == obj) return true;
    if (obj == null || getClass() != obj.getClass()) return false;
    
    Book2 other = (Book2) obj;
-   return this.title.equals(other.title) && this.publishDate.equals(other.publishDate);
+   return Objects.equals(this.title, other.title) && Objects.equals(this.publishDate, other.publishDate);
}

Objects.equals 사용을 위해 import문도 추가해야 합니다:

+import java.util.Objects;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Book2 other = (Book2) obj;
return this.title.equals(other.title) && this.publishDate.equals(other.publishDate);
}
// add this among your other imports
import java.util.Objects;
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Book2 other = (Book2) obj;
return Objects.equals(this.title, other.title)
&& Objects.equals(this.publishDate, other.publishDate);
}
🤖 Prompt for AI Agents
In src/main/java/com/survivalcoding/assignments_01_instance/exam01/Book2.java
around lines 41 to 47, the equals method risks a NullPointerException if title
or publishDate is null. To fix this, add null-safe checks by replacing direct
equals calls with Objects.equals for both title and publishDate comparisons.
Also, add the necessary import for java.util.Objects at the top of the file.


@Override
public int hashCode() {
return title.hashCode() + publishDate.hashCode();
}
Comment on lines +49 to +52
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

hashCode 메서드에서 null 포인터 예외 위험이 있습니다.

title이나 publishDate가 null인 경우 NullPointerException이 발생할 수 있습니다. 또한 현재 구현은 hashCode 계산에서 충돌 가능성이 높습니다.

다음과 같이 수정하여 null 안전성과 더 나은 해시 분산을 보장하세요:

@Override
public int hashCode() {
-   return title.hashCode() + publishDate.hashCode();
+   return Objects.hash(title, publishDate);
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@Override
public int hashCode() {
return title.hashCode() + publishDate.hashCode();
}
@Override
public int hashCode() {
return Objects.hash(title, publishDate);
}
🤖 Prompt for AI Agents
In src/main/java/com/survivalcoding/assignments_01_instance/exam01/Book2.java
around lines 49 to 52, the hashCode method risks NullPointerException if title
or publishDate is null and has a high collision probability. To fix this, modify
the method to check for null values before calling hashCode on these fields and
use a standard formula like multiplying one hash by a prime number before adding
the other to improve hash distribution and reduce collisions.


@Override
public int compareTo(Book2 other) {
return this.publishDate.compareTo(other.publishDate);
}
Comment on lines +54 to +57
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

compareTo 메서드에서 null 포인터 예외 위험이 있습니다.

this.publishDate가 null인 경우 NullPointerException이 발생할 수 있습니다.

다음과 같이 수정하여 null 안전성을 보장하세요:

@Override
public int compareTo(Book2 other) {
-   return this.publishDate.compareTo(other.publishDate);
+   if (this.publishDate == null && other.publishDate == null) return 0;
+   if (this.publishDate == null) return -1;
+   if (other.publishDate == null) return 1;
+   return this.publishDate.compareTo(other.publishDate);
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@Override
public int compareTo(Book2 other) {
return this.publishDate.compareTo(other.publishDate);
}
@Override
public int compareTo(Book2 other) {
if (this.publishDate == null && other.publishDate == null) return 0;
if (this.publishDate == null) return -1;
if (other.publishDate == null) return 1;
return this.publishDate.compareTo(other.publishDate);
}
🤖 Prompt for AI Agents
In src/main/java/com/survivalcoding/assignments_01_instance/exam01/Book2.java
around lines 54 to 57, the compareTo method risks throwing a
NullPointerException if this.publishDate is null. To fix this, add null checks
before calling compareTo on publishDate. Implement logic to handle cases where
either this.publishDate or other.publishDate is null, ensuring the method
returns a consistent ordering without throwing exceptions.


public Book2 clone() {
return new Book2(
this.title, (Date) this.publishDate.clone(), this.comment
);

}
Comment on lines +59 to +64
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

clone 메서드에서 null 포인터 예외 위험이 있습니다.

publishDate가 null인 경우 61번 라인에서 NullPointerException이 발생할 수 있습니다.

다음과 같이 수정하여 null 안전성을 보장하세요:

public Book2 clone() {
    return new Book2(
-           this.title, (Date) this.publishDate.clone(), this.comment
+           this.title, this.publishDate != null ? (Date) this.publishDate.clone() : null, this.comment
    );
}
🤖 Prompt for AI Agents
In src/main/java/com/survivalcoding/assignments_01_instance/exam01/Book2.java
around lines 59 to 64, the clone method risks a NullPointerException if
publishDate is null. To fix this, add a null check before cloning publishDate;
if publishDate is null, pass null instead of calling clone on it. This ensures
null safety when creating the new Book2 instance.

}



Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.survivalcoding.assignments_01_instance.exam01;

public class Computer extends TangibleAsset {
private String makerName;

public String getMakerName() {
return makerName;
}

public void setMakerName(String makerName) {
this.makerName = makerName;
}

public Computer(String name, int price, String color, String makerName) {
super(name, price, color);
this.makerName = makerName;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.survivalcoding.assignments_01_instance.exam01;

public class GreatWizard {
private int mp = 150;

public int getMp() {
return mp;
}
public void setMp(int mp) {
this.mp = mp;
}

void heal (Hero hero) {
if (mp >= 5) {
mp -= 5;
hero.setHp(hero.getHp() + 25);

System.out.println("HP: "+ hero.getHp());
}

else {
System.out.println("마나가 부족합니다.");
}
}

void superHeal (Hero hero) {
if (mp >= 50) {
mp -= 50;
hero.setHp(hero.getMaxHp());

System.out.println("HP: "+ hero.getHp());
}

else {
System.out.println("마나가 부족합니다.");
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.survivalcoding.assignments_01_instance.exam01;

public class Hero {
private String name;
private int hp=50;
private int maxHp=100;

public int getMaxHp() {
return maxHp;
}

public void setMaxHp(int maxHp) {
this.maxHp = maxHp;
}
Comment on lines +12 to +14
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

maxHP 설정 시 검증 로직 추가 권장

setMaxHp 메소드에서 음수 값이나 0 값에 대한 검증이 없습니다. 게임 캐릭터의 최대 HP는 양수여야 합니다.

다음과 같은 검증을 추가하는 것을 권장합니다:

 public void setMaxHp(int maxHp) {
+    if (maxHp <= 0) {
+        throw new IllegalArgumentException("maxHp는 0보다 커야 합니다.");
+    }
     this.maxHp = maxHp;
+    // 현재 HP가 새로운 maxHP를 초과하는 경우 조정
+    if (this.hp > maxHp) {
+        this.hp = maxHp;
+    }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public void setMaxHp(int maxHp) {
this.maxHp = maxHp;
}
public void setMaxHp(int maxHp) {
if (maxHp <= 0) {
throw new IllegalArgumentException("maxHp는 0보다 커야 합니다.");
}
this.maxHp = maxHp;
// 현재 HP가 새로운 maxHP를 초과하는 경우 조정
if (this.hp > maxHp) {
this.hp = maxHp;
}
}
🤖 Prompt for AI Agents
In src/main/java/com/survivalcoding/assignments_01_instance/exam01/Hero.java
lines 12 to 14, the setMaxHp method lacks validation for the maxHp parameter. To
fix this, add a check to ensure maxHp is greater than zero before assigning it
to this.maxHp. If the value is invalid (zero or negative), you can either throw
an IllegalArgumentException or ignore the assignment to maintain data integrity.


public String getName() {
return name;
}

public void setName(String name){
this.name = name;
}

public int getHp(){
return hp;
}

public void setHp(int hp){
this.hp = hp;
}
Comment on lines +28 to +30
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

HP 설정 시 검증 로직 추가 권장

현재 setHp 메소드는 어떤 값이든 받아들입니다. 게임 캐릭터의 경우 다음과 같은 검증이 필요할 수 있습니다:

  • HP는 0 이상이어야 함
  • HP는 maxHP를 초과하지 않아야 함

다음과 같은 검증 로직을 고려해보세요:

 public void setHp(int hp){
+    if (hp < 0) {
+        this.hp = 0;
+    } else if (hp > maxHp) {
+        this.hp = maxHp;
+    } else {
         this.hp = hp;
+    }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public void setHp(int hp){
this.hp = hp;
}
public void setHp(int hp){
if (hp < 0) {
this.hp = 0;
} else if (hp > maxHp) {
this.hp = maxHp;
} else {
this.hp = hp;
}
}
🤖 Prompt for AI Agents
In src/main/java/com/survivalcoding/assignments_01_instance/exam01/Hero.java
around lines 28 to 30, the setHp method currently accepts any integer value
without validation. Modify setHp to include validation that ensures hp is not
set below 0 and does not exceed the maxHP value of the hero. If the input hp is
less than 0, set hp to 0; if it is greater than maxHP, set hp to maxHP. This
will maintain valid HP values for the game character.

}
Loading