Char 형식으로 받아올 때 배열과 비교하려면 배열 안에 있는 내용은 String 형식이기 때문에 char 형식을 String 형식으로 바꿔준 후에 equals()를 사용해 비교해야 함
package day11;
// 캡슐화
class Student {
private String name; // 접근자, 접근제한자
private int score;
Student(String name, int score){
this.name = name;
this.score = score;
}
// 캡슐화된 멤버변수의 값을 가져오고 싶을 때 == getter
public String getName(){ // getXxx()
return this.name;
}
public int getScore(){
return this.score;
}
// 캡슐화된 멤버변수에게 새로운 값을 부여하고 싶을 때 == setter
public void setName(String name){
this.name = name;
}
public void setScore(int score){
this.score = score;
}
}
public class Test01 {
public static void main(String[] args) {
Student s1 = new Student("티모", 50);
Student s2 = new Student("모르가나", 80);
//System.out.println(s2.score);
System.out.println(s2.getScore());
//s1.score=81;
s1.setScore(81);
}
}
package day11;
class Circle{
private String name;
private int radius;
double area;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
this.area = this.radius * this.radius * 3.14;
}
public double getArea() {
return area;
}
public void setArea(double area) {
this.area = area;
}
Circle(String name, int radius){
this.name = name;
this.radius = radius;
this.area=this.radius*this.radius*3.14;
}
}
public class Test02 {
public static void main(String[] args) {
// 1. 원 전체출력
// 2. 원 1개 선택 반지름 바꾸고
// 넓이 바뀐 것 확인
Circle[] datas = new Circle[2];
datas[0] = new Circle("도넛",1);
datas[1] = new Circle("피자", 10);
for(int i=0; i<datas.length; i++){
System.out.println(datas[i].getName() + " " + datas[i].getArea());
}
int num = 1;
datas[num-1].setRadius(100);
System.out.println(datas[num-1].getArea());
}
}
package day11;
// [ 상속 ]
class Animal { // 상위 클래스, 부모 클래스
String name;
String type;
void hello(){
System.out.println("멍멍!");
}
}
class Dog extends Animal { // 하위 클래스, 자식 클래스, 파생 클래스
void play(){
System.out.println("!!@#!@$!@%!@%");
}
}
class Cat extends Animal {
void sleep(){
System.out.println("zzz......");
}
}
public class Test03 {
public static void main(String[] args) {
Dog dog = new Dog();
}
}
package day11;
class Point {
int x;
int y;
Point(int x, int y) { // 부모에 생성자를 추가하면 자식에 에러 생김
this.x = x;
this.y = y;
}
}
class ColorPoint extends Point {
String color;
ColorPoint() { // 기본생성자 만드니 12번 에러가 14번으로 내려옴
/*기본 생성자를 눈에 안 보이니 12번째에 에러가 생겼던 거임
자식 클래스의 모든 생성자는 무조건 가장 먼저 부모의 기본 생성자를 호출함
해결 방법 1. 부모 클래스에게 기본 생성자를 선언
(추천) 2. 자식 클래스가 부모 클래스가 가지고 있는 다른 생성자를 호출
생성자 이슈가 상속에서 가장 중요한 이슈다!!! ★★★
*/
super(10, 20); // 부모의 기본 생성자가 에러의 원인!!!
// 부모의 기본 생성자가 없어서 생긴 에러임
}
}
public class Test04 {
}
기본 생성자를 눈에 안 보이니 12번째에 에러가 생겼던 거임
자식 클래스의 모든 생성자는 무조건 가장 먼저 부모의 기본 생성자를 호출함
해결 방법 1. 부모 클래스에게 기본 생성자를 선언
(추천) 2. 자식 클래스가 부모 클래스가 가지고 있는 다른 생성자를 호출
package day11.class03;
class Person {
private String name;
Person(String name){
this.name = name;
}
void hello(){
System.out.println("안녕하세요!");
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
}
class Student extends Person{
int score;
Student(String name){
this(name,0);
}
Student(String name, int score){
super(name);
this.score = score;
}
@Override // 어노테이션 annotation
void hello(){ // 부모 크래스가 가진 메서드를
System.out.println("ㅎㅇㅎㅇ"); // 자식 클래스의 특성에 맞게 재정의
} // 메서드 재정의 == 오버라이딩 : 상속 관계에서만 발생, 메서드 시그니쳐가 동일
void hello(String msg){ // 오버로딩
System.out.println(msg); // 오버로딩과 오버라이딩 구분하는거 중요 ★
}
public int getScore(){
return score;
}
public void setScore(int score){
this.score = score;
}
}
public class Test01 {
public static void main(String[] args) {
Student s = new Student("홍길동", 81);
System.out.println(s.getName());
s.hello();
s.setScore(90);
}
}
package day11.class03;
class Shape {
String name;
double area;
Shape(String name){
this.name = name;
this.area = 0.0;
}
void draw(){
System.out.println("모양대로 그림그리기");
}
}
class Rect extends Shape {
int x;
int y;
Rect(int x){
this(x,x);
}
Rect(int x, int y){
super("사각형");
this.x = x;
this.y = y;
}
@Override
void draw(){
System.out.println("사각형 그림 그리기");
}
}
class Circle extends Shape {
int radius;
static final double PI=3.14;
Circle(int radius){
super("원");
this.radius = radius;
this.area = this.radius * this.radius * Circle.PI;
}
@Override
void draw(){
System.out.println("원 그림 그리기");
}
}
public class Test02 {
}
package day11.class03;
/*
* Animal 부모 클래스 ( 종, 이름)
* 만약, 이름을 붙여주지 않으면 이름이 종을 따라가게 해주세요
* 모든 동물은 eat() 밥을 먹습니다.
* Dog Cat
* play() sleep()
*
* 강아지만이 가지는, 고양이만이 가지는 특성을 하나씩 더 추가해주세요!
* */
class Animal{
String type;
String name;
Animal(String type, String name){
this.type = type;
this.name = name;
}
Animal(String type){
this(type, type);
}
void eat(){
System.out.println("밥을 먹습니다.");
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Dog extends Animal {
int size; // 강아지 크기
Dog(String name){
super("강아지", name);
this.size = 100;
}
Dog(){ // 기본 생성자
super("강아지");
this.size = 100;
}
@Override
void eat(){
System.out.println(this.name + " 이(가) 밥을 먹습니다.");
}
void play(){
System.out.println(this.name + " 이(가) 놀고 있습니다.");
}
void sleep(){
System.out.println(this.name + " 이(가) 자고 있습니다.");
}
}
class Cat extends Animal {
int size;
Cat(String name){
super("고양이", name);
this.size = 35;
}
Cat(){
super("고양이");
this.size = 35;
}
@Override
void eat(){
System.out.println(this.name + " 이(가) 밥을 먹습니다.");
}
void play(){
System.out.println(this.name + " 이(가) 놀고 있습니다.");
}
void sleep(){
System.out.println(this.name + " 이(가) 자고 있습니다.");
}
}
public class Test03 {
public static void main(String[] args) {
Dog dog1 = new Dog("멍멍이");
Dog dog2 = new Dog();
Cat cat1 = new Cat("야옹이");
Cat cat2 = new Cat();
dog1.eat();
dog1.play();
dog1.sleep();
cat1.eat();
cat1.play();
cat1.sleep();
dog2.eat();
dog2.play();
dog2.sleep();
cat2.eat();
cat2.play();
cat2.sleep();
}
}
package day11.class04;
import java.util.Random;
/*
* 포켓몬 클래스가 있습니다.
* 이름 별명 타입 레벨 경험치
* 피카츄 츄 전기 5 0~100
* 포켓몬 정보 출력 예쁘게 잘 될 수 있게
* 별명만 지정가능
* 별명을 지정안했다면 이름을 따라가게 설정
* 기본 경험치 0 레벨 5
*
* 피카츄 파이리 꼬부기 ... <<<<<<<<<
*
* 포켓몬은 play() 50% 성고 ㅇ실패
* 실패하면 앙무일 xxx
* 성공하면 50~500 사이의 경험치 획든
*
* 레벨업 하면 울음소리() >> 피카피카 꼬북꼬북
*
* 3마리 생성
* 각각 1번씩 게임
* 배열 XXX
* */
class Pokemon {
private String name; // 이름
private String nickname; // 별명
private String type; // 타입(물,불,전기 등)
private int level; // 레벨
private int exp; // 경험치
Pokemon(String name, String type) { // 별명X 오버로딩
this(name, name, type);
}
Pokemon(String name, String nickname, String type) { //생성자
this.name = name;
this.nickname = nickname;
this.type = type;
this.level = 5;
this.exp = 0;
}
/*
오버로딩으로 별명 지정 안 했을 때 이름 따라가게 설정
기본 경ㅇ험치 0 레벨 5로 지정ㅇ getter setter 쓰면 되려나
피카츄랑 꼬부기 파이리 미리 만들기
play() 성공이랑 실패는 반반 성공하면 50~500 랜덤 경험치 획득
if(레벨업) 울음소리() >> 피카츄는 피카피카 이런식으로
게임 1번씩 진행 배열은 쓰지 말 것
*/
// 이름 Getter/Setter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// 별명 Getter/Setter
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
// 타입 Getter/Setter
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
// 레벨 Getter/Setter
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
// 경험치 Getter/Setter
public int getExp() {
return exp;
}
public void setExp(int exp) {
this.exp = exp;
}
//울음소리
void cry() {
System.out.println("포켓몬이 운다");
}
void printInfo() { // 정보 출력 함수
System.out.println("====================");
System.out.println("이름: " + this.name);
System.out.println("별명: " + this.nickname);
System.out.println("타입: " + this.type);
System.out.println("레벨: " + this.level);
System.out.println("경험치: " + this.exp);
System.out.println("====================");
}
// 게임 플레이 함수
void play() {
if (Math.random() <= 0.5) { // 50% 이하로 실패
System.out.println(this.name + "[" + this.nickname + "]" + "와(과)의 놀이에 실패했습니다.");
return; // 실패하면 그냥 끝
}
Random random = new Random();
int Exp = random.nextInt(451) + 50; // 50~500 사이 경험치
System.out.println(this.name + "[" + this.nickname + "]" + "와(과)의 놀이에 성공했습니다!");
System.out.println("경험치를 " + Exp + " 만큼 획득했습니다!");
this.exp += Exp;
// 경험치가 100 이상인 동안 계속 레벨업
// 얼마나 반복할 줄 모르기 때문에
while (this.exp >= 100) {
this.level++;
this.exp -= 100;
System.out.println("레벨업 완료! 현재 레벨: " + this.level);
cry(); // 레벨업 할 때마다 울기
}
}
}
// 피카츄 상속
class Pika extends Pokemon {
Pika(String nickname) {
super("피카츄", nickname, "전기");
}
Pika() { // 별명 지정
this("버스카드충");
}
@Override
public void cry() {
System.out.println("피카피카!");
}
}
// 파이리 상속
class fire extends Pokemon {
fire(String nickname) {
super("파이리", nickname, "불"); // 기본설정, 별명 지정받기
}
fire() { // 별명 지정
this("이파리");
}
@Override
void cry() {
System.out.println("초코파이!");
}
}
// 꼬북이 상속
class turtle extends Pokemon {
turtle(String nickname) {
super("꼬부기", nickname, "물"); // 기본설정, 별명 지정받기
}
turtle() { // 별명 지정
this("속이 거북");
}
@Override
void cry() {
System.out.println("꼬북꼬북!");
}
}
public class Test03 {
public static void main(String[] args) {
Pokemon pika = new Pika("라이츄");
Pokemon fire = new fire("파이어");
Pokemon turtle = new turtle(); // 별명 없이 생성 예시
// 게임 시작 전
System.out.println("=== 게임 시작 전 포켓몬 정보 ===");
pika.printInfo(); // 피카츄 정보
fire.printInfo(); // 파이리 정보
turtle.printInfo(); // 꼬북이 정보
// 게임 진행 중
System.out.println("\n=== 게임 진행 ===");
pika.play(); // 피카츄 게임
fire.play(); // 파이리 게임
turtle.play(); // 꼬북ㅇ이 게임
// 게임 종료 후
System.out.println("\n=== 게임 후 포켓몬 정보 ===");
pika.printInfo(); // 게임 후 피카츄 정보
fire.printInfo(); // 게임 후 파이리 정보
turtle.printInfo(); // 게임 후 꼬북이 정보
}
}
'Back-End' 카테고리의 다른 글
| [JAVA] 3중 상속과 인터페이스 (4) | 2025.01.17 |
|---|---|
| [JAVA] 기초 공부 10 (1) | 2025.01.15 |
| [JAVA] 기초 공부 8 (1) | 2025.01.13 |
| [JAVA] 기초 공부 8(객체지향) (0) | 2025.01.10 |
| [JAVA] 기초 공부 7(MVC, 오버로딩) (1) | 2025.01.09 |