Java 20221103

신래은·2022년 12월 15일

JAVA

목록 보기
13/22

DAY 14

Polymorphism

Main Class

public class PersonMain {
    public static void main(String[] args) {
        // Person 클래스 타입으로 Developer, Designer 클래스 타입의 객체를 생성할 수 있는 것을
        // "다형성"이라고 한다.
        Person p1 = new Developer("user ", "female", "Java");
        Person p2 = new Designer("user1 ", "male", "Illustrator");
        // 기존 클래스 Person에 있는 work의 기능을
        // Developer와 Designer 클래스에서 기능을 다시 만들었다(재정의)
        // 이것을 오버라이딩 이라고 한다.
        p1.work(); // Developer 클래스의 work가 실행된다.
        p2.work(); // Designer 클래스의 work가 실행된다.
    }
}

Designer Class

public class Designer extends Person {
    String tool;
    public Designer (){}
    public Designer (String name, String gen, String tool ){
        super(name, gen);
        this.tool =tool;
    }
    void work(){
        System.out.println(name + "은(는) " + tool + "로 디자인을 한다.");
    }
}

Developer Class

public class Developer extends Person {
    String language;
    public Developer (){}
    public Developer (String name, String gen, String language){
        super(name, gen);
        this.language = language;
    }
    void work (){
        System.out.println(name + "은(는) " + language + "로 프로그램을 개발한다.");
    }
}

Person

// person class (name, gen)
// work() 기능
// Developer class(language)
// work() 기능 오버라이드
// (language로 프로그램을 개발한다.)
// Designer class(tool)
// work() 기능 오버라이드
// (tool로 디자인을 한다.)
public class Person {
    String name;
    String gen;
    public Person (){}
    public Person (String name, String gen ){
        this.name = name;
        this.gen = gen;
    }
    void work() {
        System.out.println("일을한다.");
    }
}

BoardPostEx

import java.text.SimpleDateFormat;
import java.util.Date;

// 게시글 정보
public class BoardPost {
	// class 변수, 객체가 생성되지 않아도 클래스 이름.변수이름 방법으로 사용가능
    // 모든 BoardPost 타입의 객체들이 공유. 이 변수는 단 1개만 존재한다.
    static int next_no = 37565;
    Integer post_no; // 글 번호
    String post_title; // 글 제목
    String post_content; // 글 내용
    Date post_reg_dt; // 글 등록일
    Date post_mod_dt; // 글 수정일
    String post_author; // 작성자
    Integer post_count; // 조회수
    String post_pwd; // 게시글 비밀번호

    public BoardPost (String title, String content, String author, String pwd ) {
        post_pwd = pwd;
        post_no = next_no;
        post_title = title;
        post_content = content;
        post_author = author;
        post_reg_dt = new Date(); // 글 등록일을 객체를 만든 시간으로 설정
        post_mod_dt = new Date(); // 글 수정일을 객체를 만든 시간으로 설정
        post_count = 0;
        next_no++;
    }
    void showPostInfo (boolean detail) {
        System.out.print(post_no + "\t");
        System.out.print(post_title + "\t");
        System.out.print(post_author + "\t");
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // Date의 형식을 지정해줌
        System.out.print(f.format(post_reg_dt) + "\t");
        if (detail) {
            System.out.print(f.format(post_mod_dt) + "\t");
        }
        System.out.println(post_count);
        if (detail) {
            System.out.println("---------------------------------------");
            System.out.println(post_content);
            System.out.println("---------------------------------------");
        }
    }
}

BoardCommentEx

import java.text.SimpleDateFormat;
import java.util.Date;

public class BoardComment {
    Integer post_no;
    String comment;
    Date reg_dt;
    String author;
    String pwd;
    
    public BoardComment () {}
    public BoardComment (Integer post_no, String comment, String author, String pwd) {
        this.post_no = post_no;
        this.comment = comment;
        this.author = author;
        this.pwd = pwd;
        reg_dt = new Date();    
    }
    public void printCommentInfo(){
        System.out.println(author);
        System.out.println(comment);
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(f.format(reg_dt));
    }
}

BoardMain

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;

public class BoardMain {
   public static List<BoardPost> postList =  new ArrayList<BoardPost>();
   static Scanner s = new Scanner(System.in);
   public static List<BoardComment> commentList = new ArrayList<BoardComment>();
   public static void main(String[] args) {
       
       initializeBoardPost(10);
       while(true) {
           printPostList();
           System.out.print("1. 글 쓰기, 2.글 상세보기, 3. 글 삭제, 4. 글 수정, 0. 종료 : ");
           int sel = s.nextInt();
           s.nextLine();
           switch(sel) {
               case 1:
                   addPost();
                   break; 
               case 2:
                   printPostDetail();
                   break;
               case 3:
                   deletePost();
                   break;
               case 4:
                   updatePost();
                   break;
               case 0:
                   System.out.println("종료합니다.");
                   return;
               default : 
                   System.out.println("잘못된 메뉴 번호 입니다.");
           }
       }
   }

   public static void initializeBoardPost(int count) {
       for(int i=0;i<count; i++){
           postList.add(new BoardPost("DummyTitle" + i, "DummyContent" + i, "author", "1234" ));
       }
   }
   
   public static void addPost(){
       System.out.print("글 제목 : ");
       String title = s.nextLine();
       System.out.print("글 내용 : ");
       String content = s.nextLine();
       System.out.print("글 작성자 : ");
       String author = s.nextLine();
       System.out.print("글 비밀번호 : ");
       String pwd = s.nextLine();
       System.out.println("글을 등록하시겠습니까? (y/n) : ");
       String confirm = s.nextLine();
       if(confirm.equalsIgnoreCase("y")) {
           postList.add(new BoardPost(title, content, author, pwd));
           System.out.println("글이 등록되었습니다.");
       }
       else {
           System.out.println("글 등록이 취소되었습니다.");
       }
   }
           
   public static void printPostList (){
       System.out.println("글번호\t글제목\t\t작성자\t\t등록일\t\t조회수");
       for(BoardPost p : postList){
           p.showPostInfo(false); // 간단한 정보만 보여주기
       }
   }

   public static void updatePost(){
       System.out.print("수정할 글 번호 : ");
       int n = s.nextInt();
       s.nextLine();
       BoardPost p = searchPostDetailByNumber(n); // n 번 글이 존재하는지 파악, p는 n번 글 정보
       
       System.out.print("글 비밀번호 : ");
       String pwd = s.nextLine();
       if (p.post_pwd.equals(pwd)){
           System.out.print("글 제목 : ");
           String title = s.nextLine();
           if (title.equals("")){
               title = p.post_title;
           }
           System.out.print("글 내용 : ");
           String content = s.nextLine();
           if (content.equals("")){
               content = p.post_content;
           }
           
           System.out.println("글을 수정하시겠습니까? (y/n) : ");
           String confirm = s.nextLine();
           if(confirm.equalsIgnoreCase("y")) {
               p.post_title = title;
               p.post_content = content;
               p.post_mod_dt = new Date();
               System.out.println("글이 수정되었습니다.");
           }
       }
       else {
           System.out.println("수정에 실패했습니다. (비밀번호 오류)");
       }
   }

   public static void printPostDetail(){
       System.out.print("글 번호 : ");
       int n = s.nextInt();
       s.nextLine();
       BoardPost p = searchPostDetailByNumber(n);  // n 번글이 존재한다면 p에 그 정보를 입력
       if (p != null) { // n 번 글이 존재한다면,
           p.post_count++; // 조회수 올리고,
           p.showPostInfo(true); // 상세정보 표시
           System.out.println("== 댓글 ==");
           showComments(p.post_no); // 댓글 표시

           System.out.print("1.댓글쓰기  0.목록으로");
           int sel = s.nextInt();
           s.nextLine();
           if(sel == 1) {
               addComment(p.post_no);
           }
       }
   }

   public static void addComment(Integer post_no) {
       System.out.print("댓글 내용 : ");
       String comment = s.nextLine();
       System.out.print("작성자 : ");
       String author = s.nextLine();
       System.out.print("비밀번호 : ");
       String pwd = s.nextLine();
       System.out.print("댓글을 등록하시겠습니까? (y/n) : ");
       String confirm = s.nextLine();
       if(confirm.equalsIgnoreCase("y")) {
           commentList.add(new BoardComment(post_no, comment, author, pwd));
       }
   }

   public static void deletePost() {
       System.out.print("삭제할 글 번호 : ");
       int n = s.nextInt();
       s.nextLine();
       BoardPost p = searchPostDetailByNumber(n);
       if (p != null) {
           p.showPostInfo(true); // 상세정보 표시
           System.out.print("삭제하시겠습니까? (y/n) : ");
           String confirm = s.nextLine();
           if(confirm.equalsIgnoreCase("y")) {
               System.out.print("글 비밀번호 : ");
               String pwd = s.nextLine();
               if (p.post_pwd.equals(pwd)){
                   postList.remove(p);
                   System.out.println("삭제되었습니다.");
               }
               else {
                   System.out.println("삭제에 실패했습니다. (비밀번호 오류)");
               }
           }
           else {
               System.out.println("글 삭제가 취소되었습니다.");
           }
       }
   }

   public static BoardPost searchPostDetailByNumber(int post_no) {
       for (BoardPost p : postList) {
           if(p.post_no == post_no) {
               // p.post_count++; // 조회수 증가
               // p.showPostInfo(true);
               return p;
           }
       }
       System.out.println(post_no + "번 글은 존재하지 않습니다.");
       return null;
   }

   public static void showComments(Integer post_no) {
       for(BoardComment c : commentList) {
           if(c.post_no == post_no) {
               c.printCommentInfo();
               System.out.println("=======================================");
           }
       }
   }
}

0개의 댓글