728x90

객체 생성할 때는 생성자를 참고하세요!

import java.util.Scanner;

public class Rectangle {

        //가로, 세로 면적

        //면적 구하기

        //면적 출력

        

        Scanner sc = new Scanner(System.in);

        int width;

        int height;

        int area;

        

        public void input() {

                System.out.print("가로 값을 입력해주세요 : ");

                width= sc.nextInt();

                System.out.print("세로 값을 입력해주세요 : ");

                height= sc.nextInt();

}

        public Rectangle(int width, int height) {

                super();

                this.width = width;

                this.height = height;

        }

        public void area() {

                area = width * height;

        }

        

        public void print() {

                System.out.println("면적은 "+area +"입니다.");

        }

}

 

public class RectangleMain {

        public static void main(String[] args) {

                Rectangle rec = new Rectangle(0, 0);

                rec.input();

                rec.area();

                rec.print();

        }

}

 

멤버변수는 초기화 안해도 됨. (defalut값을 기본적으로 가짐)

지역변수는 반드시 초기화 해야함.

 

이름은 서로 같은데 파라미터 수와 순서와 타입이 다를 때 =>오버로딩

public void area(){}

public void area(int x){} -> 오버로딩 구현. 두개의 메소드를 서로 다른 것으로 인지

 

생성자 안에서 다른 생성자를 호출하기 위해서는 ->this(파라미터) 사용

this(name, id, password); 생성자의 호출문은 생성자 안에서 첫번째 명령문이어야 함.

 

 

-접근제어자(access modifier) :  (243p) - 코드의 안정성을 위해

Public  > Protected > (default) > private 

private : 같은 클래스내에 접근 가능

default : 같은 패키지 내에서 접근 가능

protected : 같은 패키지 내에서, 그리고 다른 패키지의 자손클래스에서 접근가능

public : 접근 제한이 전혀 없다.

 

캡슐화(정보은닉) 특정 멤버변수의 접근을 제어하기 위해 private을 사용하면 간접적으로 우회하여 사용하도록 get,set메소드를 사용

멤버변수를 private사용해 다른 클래스에서 접근하고 싶으면 그 get,set메소드를 사용해서 우회해야 함.

setter, getter메소드 //source - generate setter/getter (244~245p)

 

public class Member {

        private String name;

        private int age;

        

        public String getName() {

                return name;

        }

        public void setName(String name) {

                this.name = name;

        }

        public int getAge() {

                return age;

        }

        public void setAge(int age) {

                this.age = age;

        }

        public Member() {}

}

 

public class MemberMain {

        public static void main(String[] args) {

                Member m = new Member();

                m.setName("홍길동");

                m.setAge(22);

                

                System.out.println(m.getName());

                System.out.println(m.getAge());

        }

}

홍길동

22

 

멤버변수가 private할때 그 밑에 set, get메소드를 설정해줘서 다른 클래스에서 우회해서 부를때 사용함.

상수는 꼭 final을 선언해줘야 함.

 

 

**예외처리

-Exception /예외발생 실행순서 1->3->4->5(예외처리해줌) 2만빼고 실행, 예외아닐때 1->2->4->5->

try{ 1

2

{catch(예외클래스}3

예외발생시 실행문장, 예외메시지 출력

}

finally{예외가 발생하든안하든 실행되는 문장4

}

5

 

 

각각의 오류를 보고 싶을 때는 catch문을 2개 이상 써주기.

보통은 예외처리 한번만 써줌 catch(exception처리)

예외처리 안하면 호출한데가서 부모클래스로 가게 됨.

예외회피 int getAverage() throws(예외) - 자기가 처리안하고예외를 회피함 ->부모클래스에서 처리해야함. 

예외를 한곳에 모아서 처리하고 싶을때

 

인위적으로 인셉션 발생시키기 (자바문법적으로는 올바름)

출금하고 싶은 돈> 잔액 : 잔액이부족합니다!! thorw발생, thorws로 던짐 ->try catch로 예외처리해줘야함.

 

 

  public int withdraw(int amount) throws Exception {  //throws : 자신의 예외를 자신이 처리하지 않고 회피

          if(balance<amount) {

                  throw new Exception("잔액 부족"); //thorw : 인위적으로 예외발생시킴

          }

          balance -= amount;

          return amount;

  }

 

try {   //메인함수에서 try-catch로 예외처리해줌

                 account.withdraw(15000);

         }catch(Exception e) {

                 String msg = e.getMessage();    //

                 e.printStackTrace();            //둘 중 하나쓰기 (☞더많이씀)

                 System.out.println(msg);

                

         }

->try catch + ctrl+space로 바로입력가능

 

 

-메소드 오버로딩(파라미터 수와 타입 순서만 다른 것. 메소드이름은 같음)

메소드 호출 조건 : 메소드와 메소드 호출문의 파라미터 수, 타입, 순서가 맞아야 함

->이런 특성을 이용하면 한 클래스 안에 똑같은 이름의 메소드 여러 개를 선언할 수 있음 (메소드 오버로딩)

메소드 시그니처(method signature) = 메소드 이름 + 파라미터 변수의 수 +타입+순서

 int ar = account.update(100); -> 오류전구추천버튼 눌러서 account클래스에 다음 필드 생성.

update라는 메소드가 없었음. 

 

public int update(int i) {

        // TODO Auto-generated method stub

        return 0;}

메소드의 시그니처를 먼저 생성->좋은점이 일일이 안쳐도 된다는 점.

 

 

-클래스의 정적 구성 요소(240p)

    -객체가 아니라 클래스 자체에 속하는 필드,메소드 등의 구성 요소

     -static 키워드를 사용하여 선언

 

static '클래스의', '공통적인'-공용 메모리를 한번가짐

static 1. 클래스생성될때 메모리가 올라왔다. 객체를 생성하지 않고도 변수를 생성할 수 있다.

  1. 메모리를 같이 사용한다. (공용변수라 메모리가 하나밖에 없어 데이터값이 누적되어 진다.) ->메모리 한번생성

  2. 객체를 생성하지 않고도 사용할 수 있다. 클래스에 관계된 것이기 때문이다.

-정적필드

static 멤버변수 : 모든 인스턴스에 공통적으로 사용되는 클래스 변수가 된다. 클래스 변수는 인스턴스를 생성하지 않고도 사용 가능하다. 클래스가 메모리에 로드될 때 생성된다.

static 메소드 : 인스턴스를 생성하지 않고도 호출이 가능한 static메서드가 된다. static메서드 내에서는 인스턴스멤버들을 직접 사용할 수 없다.

static 초기화 블럭 :정적 필드의 초기값 설정에 주로 사용됨클래스가 사용되기 전에 자바 가상 기계에 의해 단 한 번 호출됨 

static{}

 

->멤버 멤버를 사용하지 않는 메서드는 static을 붙여 static메서드로 선언하는 것을 고려해보자. 가능하다면 static메서드로 하는 것이 인스턴스(객체)를 생성하지 않고도 호출이 가능해서 더 편리하고 속도도 더 빠르다.

 

호출방법 -> 클래스.정적필드이름

-상수필드(한번만 생성하면 됨 - 수정삭제불가)

-★final static int UPPER_LIMIT = 10000;

 

-정적 메소드

integer.parseInt();  ->정적메소드 (인티져 클래스의 팔스인트필드)

math.Random(); ->정적메소드 (메스 클래스의 랜덤필드)

객체를 생성하지 않고도 메모리를 사용가능함.

 

public class StaticExam {

        int num; //멤버변수 ->객체생성할때 메모리 올라옴

        static int str;//static변수 ->클래스생성할때 메모리 올라옴

        

        public static void sMethod(int n) {//static 메소드 안에서는 static변수만 사용해야  함.->메모리가 생성되는 시기가 다르기 때문에.(하나는 로딩될 때(클래서 생성될 때), 하나는 객체생성될 때)

                num = n; //오류뜸(메모리가 안올라옴 : 메모리의 부재)

                str = 100;

        }

}

 

Q. 과제 (Grade & GradeMain클래스)

  1. Grade (이름, 국어, 영어, 수학, 총점, 평균) =>2명 이상의 성적 구현(배열사용)

  2. 평균구하기

  3. 출력하기

 

Q. 전화번호 관리 프로그램 (패키지 Kosta.phone)

->1인 전화번호 내역 -> 객체(상태/행동)

->상태 = 이름, 전화번호, 생년월일

->기능 = 1인 전화내역 출력기능

->클래스 : PhoneInfo

 

-> Main : 프로그램 시작

-> 추가, 출력, 검색 =>메뉴 선택

 

-> Manager클래스(추가, 출력, 검색 => 기능 구현)

 

 

**만드는 순서

멤버변수 ->디폴트생성자 -> 생성자 ->get set메소드 만들기 -> show 메소드만들기

manager객체 생성되면 ->manager생성자로 감 ->phoneinfo 배열생성됨

 

 

public class Phoneinfo {

        //상태 : 이름, 전화번호, 생년월일

        private String name;

        private String phoneNo;

        private String birth;

        

        public Phoneinfo() {}

        public Phoneinfo(String name, String phoneNo, String birth) {

                super();

                this.name = name;

                this.phoneNo = phoneNo;

                this.birth = birth;

        };

        

        //기능 : 1명의 전화내역 출력하기

        public void show() {

                System.out.println("이름 : "+name);

                System.out.println("전화번호 : "+phoneNo);

                System.out.println("생년월일 : "+birth);

                System.out.println();

        }

        

        public String getName() {

                return name;

        }

        public void setName(String name) {

                this.name = name;

        }

        public String getPhoneNo() {

                return phoneNo;

        }

        public void setPhoneNo(String phoneNo) {

                this.phoneNo = phoneNo;

        }

        public String getBirth() {

                return birth;

        }

        public void setBirth(String birth) {

                this.birth = birth;

        }

}

 

import java.util.Scanner;

public class Main {

        public static void main(String[] args) {

                //1.추가 2.출력 3.종료

                Scanner sc= new Scanner(System.in);

                Manager m =new Manager();

                

                while(true) {

                        System.out.println("1.추가 2.출력 3.검색 4.종료");

                        System.out.print("선택 : ");

                        String menu = sc.nextLine();

                        

                        switch (menu) {

                        case "1":

                                m.addPhoneinfo();

                                break;

                        case "2":

                                m.listPhoneinfo();

                                break;

                        case "3":

                                m.searchPhoneinfo();

                                break;

                        case "4":

                                System.out.println("프로그램 종료");

                                return;//main메소드 탈출

                        }//end switch

                }//end while

        }//end main()

}//end class

 

 

 

 

import java.util.Scanner;

public class Manager {

        //상태 : PhoneInfo[] arr

        //행동 : 추가, 삭제, 출력 메소드구현

        

        Phoneinfo arr[];

        Scanner sc = new Scanner(System.in);

        int count = 0;

        

        public Manager() { //메인 실행하면 객체만들기 때문에 객체에서 바로 이 생성자로 와서 객체배열 만들고자 이 안에다가 배열생성.

                arr = new Phoneinfo[10];

        }

        public void addPhoneinfo() {  //추가메소드

                                //이름, 전화번호, 생년월일 입력

                                //phoneinfo 개체 생성

                                //배열에 추가 => 인덱스 변수값으로 지정

                System.out.print("이름 : ");

                String name= sc.nextLine();

                System.out.print("전화번호 : ");

                String phoneNo= sc.nextLine();

                System.out.print("생년월일 : ");

                String birth= sc.nextLine();

                

//              Phoneinfo info = new Phoneinfo(name, phoneNo, birth);

//                      arr[count++] = info;

                arr[count++] = new Phoneinfo(name, phoneNo, birth);

                

        }

        public void listPhoneinfo() {    //출력메소드

                                //배열에 있는 모든 Phoneinfo객체 출력

                                //show()출력

                for(int i=0;i<count;i++) {

                        arr[i].show();  

                }

        }

        public void searchPhoneinfo() {    //검색메소드

                //이름의 전화번호내역이 검색되도록 한다.

//              System.out.print("검색할 이름을 입력해주세요 : ");

//              String name = sc.nextLine();

//                      for(int i=0;i<count;i++) {

//             if(name.equals(arr[i].getName()))

//             System.out.println(arr[i].getPhoneNo() + "입니다.");

//             else

//              System.out.println("찾으시는 값이  없습니다.");}

                System.out.print("검색할 이름을 입력해주세요 : ");

                String name = sc.nextLine();

                int idx = -1;

                for(int i=0;i<count;i++) {

                        Phoneinfo info = arr[i];

                        if(name.equals(info.getName())) {

                                info.show();

                                idx = i;

                        }

                }

                

                if(idx == -1) {

                        System.out.println("찾을 수 없습니다.");

                }

                

        }

}

 

과제 ->>>>>>>>>>>게시판 구현하기!!

 

게시판 구현하기

 

1개의 글 : seq(글번호), title(글제목), writer(작성자),

               contents(글내용), regdate(작성일자), hitcount(조회수)

 

1. 글쓰기

입력: 글제목, 작성자, 글내용 => Board객체 생성

 

2. 전체출력

글번호    글제목    작성자  글내용  작성자일자        조회수

 

3. 글세부조회

글번호를 통해 해당 글 조회

번호, 글제목, 작성자, 글내용, 작성일자, 조회수 => 1개 Board객체    //여기까지라도 해보기

 

4. 수정/삭제 (뒤에꺼 하나씩 땡기기)

 

5. 검색(제목, 작성자) 내가 원하는 글들만 출력

 

6. 정렬(기본) : 최근 입력 순서(내림차순)

 

7. 댓글 : 글세부기능 => 댓글쓰기 , 해당 글세부보기 => 댓글 목록

 

 

★★변수

  1. 클래스 변수 : 클래스 영역 ->클래스가 메모리에 올라갈 때 생성 -> 클래스 변수(static변수)는 객체생성 없이 '클래스 이름.클래스 변수'로 직접 사용 가능.

  2. 멤버변수  : 클래스 영역 -> 인스턴스가 생성되었을 때 생성

  3. 지역변수  : 클래스 영역 이외의 영역(메서드, 생성자, 초기화 블럭 내부) -> 변수 선언문이 수행되었을 때

 

멤버변수(클래스 안에 선언되는 변수) = 클래스 변수(static변수) + 인스턴스 변수

 

 

 

public void updatePhoneinfo() {  //수정메소드

                        System.out.print("이름 : ");

                        String name = sc.nextLine();

                        int idx = -1;

                        for(int i=0;i<count;i++) {

                                Phoneinfo info = arr[i];

                                if(name.equals(info.getName())) {//한사람의 정보

                                        System.out.print("수정 전화번호 입력 : ");

                                        String phoneNo = sc.nextLine();

                                        info.setPhoneNo(phoneNo);

                                        idx = i;

                                        break;

                                }

                        }

                        if(idx == -1)

                                System.out.println("찾을 수 없습니다.");

        }

 

 

public void deletePhoneinfo() {   //삭제메소드

                        System.out.print("이름 : ");

                        String name = sc.nextLine();

                        int idx = -1;

                        

                        for(int i=0;i<count;i++) {

                                Phoneinfo info = arr[i];

                                if(name.equals(info.getName())){

                                        idx = i;

                                        break;

                                }

                        }

                        if(idx != -1) { //마지막에서 삭제할 위치를 당기는 작업

                                for(int i=idx;i<count-1;i++) { //찾는 위치에서 마지막에서  하나뺀값까지

                                        arr[i] = arr[i+1];

                                }

                                arr[count-1] =null;

                                count--;//전체개수 -1

                        }else {

                                System.out.println("찾을 수 없습니다.")

                        }

                }

       }

 

 

 

 

 

728x90

+ Recent posts