1.  사용자 정의 메소드


 - 형식

 

 리턴형 메소드명(매개변수,...){

       실행문장;

       ...

    [return]

}

 

- 자주 반복되는 작업이나 하나의 작업을 여러개의 작업으로 쪼갤때 메소드를 만든다.



ex> 덧셈메소드 호출하여 사용.

class  Test01_Method

{

    public static void main(String[] args)

    {

        int a=10,b=20;

        int c=sum(a,b);

        System.out.println("두수합:"+c);

    }

    public static int sum(int a,int b)

    {

        int z=a+b;

        return z;

    }

}


ex> 출력 메소드 사용

class Test02_Method

{

    public static void main(String[] args)

    {

        String str="*";

        //str을 10번 출력하는 메소드

        printString(str,10);

        System.out.println("메인메소드 종료!");

    }

    public static void printString(String str,int n)

    {

        for(int i=1;i<=n;i++){

            System.out.print(str);

        }

        System.out.println();

    }

}

 

 

 


 

2. 객체 지향 프로그래밍 

 

- 모든 작업을 객체화해서 프로그래밍하는 기법

- 객체지향 프로그래밍에서는 모든 작업을 클래스로 구현한다.

- 클래스 만드는 형식

 

class 클래스명{

    멤버변수;

      ...

    멤버메소드;

      ...

}

 

 - 클래스를 사용하기 위해서는 객체를 생성해야 한다.

 

   형식 )   클래스명 객체명=new 클래스명();

 


ex>   사각형 클래스 만들기

 - 속성(멤버변수) :  x,y좌표,가로길이,세로길이,선색상,...

 - 기능(멤버메소드) :  사각형을 그리기,사각형을 칠하기,사각형크기변경,..

 

class Rect

{

    //private는 멤버를 외부(자신의 클래스를 제외한 영역)에서 접근 불가!!

    private int x,y;    //좌표

    private int w,h;    //가로세로길이

    private String color;    //선색상


    

    //public 멤버는 어디서든 접근 가능!

    public void drawRect()

    {  //사각형 그리는 기능

        System.out.println(x+","+y+"좌표에 " + 

                w +"," + h +"의 길이로"+

                color+"색상의 사각형을 그립니다.");

     }

    public void setXY(int x1,int y1)

    {    //좌표설정 메소드

         x=x1;  

         y=y1;

    }

    public void setWH(int w,int h)

    {    //가로세로길이 설정 메소드

        if(w<=0 || h<=0){

            System.out.println("가로 세로 길이가 잘못 되었어요!");

            return;

        }

        this.w=w;  this.h=h;

    }

    

    public void setColor(String color)

    {  //선색상 설정 메소드

        this.color=color;

    }

}

class  Test03_Class

{

    public static void main(String[] args)

    {

        //객체(인스턴스) 생성

        Rect rr=new Rect();

        rr.setXY(100,100);

        rr.setWH(100,300);

        rr.setColor("빨강");

  

       // rr.w=-100;

       // rr.h=100;

        rr.drawRect();

    }

}

 

 

 

 


ex> 성적처리 클래스를 만들어 보자.

- 속성 : 학생번호,국어,영어,총점,평균

- 메소드: 값저장,성적계산,데이터출력

 

import java.util.Scanner;

class Student

{

    // 멤버변수 선언(멤버변수는 private로!!! )

    private int num;

    private int kor;

    private int eng;

    private int tot;

    private double ave;


    //값을 저장하는 메소드

    public void input()

    {

        Scanner scan=new Scanner(System.in);

        System.out.println("학생번호");

        num=scan.nextInt();

        System.out.println("국어점수");

        kor=scan.nextInt();

        System.out.println("영어점수");

        eng=scan.nextInt();

    }

    //성적을 계산

    public void calc()

    {

        tot=kor+eng;

        ave=tot/2.0;

    }

    //데이터를 출력

     public void printData()

    {

        System.out.println("번호:"+num);

        System.out.println("국어:"+kor);

        System.out.println("영어:"+eng);

        System.out.println("총점:"+tot);

        System.out.println("평균:"+ave);

    }

}

class Test04_Class

{

    public static void main(String[] args)

    {

        //Student 객체 생성

        Student stu=new Student();

        stu.input();

        stu.calc();

        stu.printData();

    }

}

 

 

 

 

 

ex>  도서제목,가격,판매부수를 매개변수로 받아 멤버에 값을 저장하는 생성자를 갖는 클래스를 만들고 main에서 사용해 보세요.

 

class MyBook

{

    private String title;

    private int price;

    private int cnt;

    private int total;

 

    //디폴트생성자

    public MyBook(){}

    

    public MyBook(String title,int price,int cnt)

    {

        this.title=title;

        this.price=price;

        this.cnt=cnt;

    }

 

    public void setData(String title,int price,int cnt)

    {

        this.title=title;

        this.price=price;

        this.cnt=cnt;

    }

    public void getTotal()

    {

        total=price*cnt;

    }

    public void printBook()

    {

        getTotal();

        System.out.println("도서제목:"+title);

        System.out.println("판매가격:"+price);

        System.out.println("판매부수:"+cnt);

        System.out.println("총판매가격:"+total +"원");

    }

}


class Quiz05

{

    public static void main(String[] args)

    {

        MyBook bb=new MyBook("자바가 제일 쉬웠어요!",10000,10);

    

        //도서제목,가격,판매부수,총판매가격이 출력됨

        bb.printBook();

 

        MyBook bb1=new MyBook();

        // MyBook() dault 생성자

        bb1.setData("Jsp",10000,5);

        bb1.printBook();

    }

}

 

 

 



3. 생성자(Constructor)


- 객체가 생성될 때 (자동)으로 호출되는 메소드

- 일반적으로 멤버변수값을 초기화하려는 목적으로 만듬.


- 만드는 형식>

클래스명과 동일한 이름으로 만들고 리턴값이 없으며 void 는 쓰지 않는다.


 예)

 class AA{

      int a;

      public AA(){//생성자

       ..

      }

}

 

 

ex>  Font객체를 생성하고 값저장후 출력해 보세요.

(글꼴에 대한 정보를 갖는 클래스)

class Font

{

    //글꼴크기

    private int fontSize;

    //글꼴체

    private String fontName;

    

    //생성자

    public Font()

    {

        fontSize=9;

        fontName="바탕체";

    }

    //파라미터를 갖는 생성자 

    public Font(int size,String name)

    {

         fontSize=size;

         fontName=name;

    }

    //값설정 메소드

    public void setData(int fontSize,String fontName)

    {

         this.fontSize=fontSize;

         this.fontName=fontName;

     }

    //설정값 출력 메소드

    public void printInfo()

    {

         System.out.println("현재설정된 글꼴크기:"+fontSize);

         System.out.println("현재설정된 글꼴체:"+fontName);

         System.out.println();

    }

}

class  Test05_Class

{

    public static void main(String[] args)

    {

        //파라미터가 없는 생성자 호출

        Font ff=new Font();

        ff.printInfo();

        ff.setData(10,"굴림체");

        ff.printInfo();

  

        //파라미터가 있는 생성자 호출

        Font ff1=new Font(18,"궁서체");

        ff1.printInfo();

    }

}

 

 


 

 

'JAVA' 카테고리의 다른 글

final  (0) 2014.09.12
Overloading  (0) 2014.09.12
배열( array )  (0) 2014.09.12
반복제어문( while문 )  (0) 2014.09.12
반복제어문( for문 )  (0) 2014.09.12

+ Recent posts