[Java의 정석] - Ch.06

hybiis·2023년 3월 27일
0

Java

목록 보기
1/3

✔️ 클래스와 객체

클래스 : 객체를 정의한 것
객체 : 실제로 존재하는 것

ex)

클래스객체
제품 설계도제품
TV설계도TV
붕어빵 기계붕어빵

인스턴스 : 클래스로부터 만들어진 객체

  • 객체의 구성요소
    1.속성 : 멤버변수, 특성, 필드, 상태
    2.기능 : 메서드, 함수, 행위

ex) Tv클래스의 속성과 기능

class Tv{
			//속성(변수) 
            String color; //색
            boolean power; //전원상태
            int channel; //채널
            
            //기능(메서드)
            void power(){
                power=!power;
            } //전원끄고켜기
            void channelDown(){
                channel--;
            }//채널 내리기     
            void channelUp(){
                channel++;
            }//채널 올리기
        }
class TvTest {
        public static void main(String[] args) {
            Tv t= new Tv(); //참조변수 t선언 후 인스턴스 생성
            t.channel=7; //tv인스턴스 멤버변수 값 지정
            t.channelUp(); //tv인스턴스 메서드 호출
            System.out.println("채널의 값은 "+t.channel+" 입니다.");
        }
    }

출력결과

채널의 값은 8 입니다.

✔️ 변수와 메서드

  • 인스턴스 변수와 클래스 변수

    변수선언위치저장공간특징
    인스턴스클래스독립적서로 다른값을 가질 수 있음
    클래스클래스공통static과 함께 선언해야함
  • 클래스 변수는 객체 생성 없이 '클래스이름.클래스변수명' 을 통해 직접 사용가능

public class Card {
    //고유값을 가져야 하는 카드의 무늬와 숫자는 인스턴스변수로 선언
    String kind;
    int number;
    //공통된 값을 가져야하는 길이와 폭은 클래스 변수로 선언
    static int width=100;
    static int hight=200;
}
class CardTest{
    public static void main(String[] args) {
        //인스턴스 객체 생성
        Card cl =new Card();
        cl.kind="heart";
        cl.number=7;

        System.out.println("카드 cl은 "+cl.kind+", "+cl.number+"이며 크기는 ("+Card.hight+", "+Card.width+") 입니다.");
    }
}

출력결과

카드 cl은 heart, 7이며 크기는 (200, 100) 입니다.
  • 메서드
    선언부구현부로 이루어짐
  • 메서드의 반환타입
    결과의 반환값이 없는 경우 void를 적음
  • 메서드의 return문
    반환타입이 void가 아닌 경우 꼭 'return 반환값'을 적어줘야함
//선언부
int add(int a,int b){ //반환타입 메서드 이름(타입 변수명, 타입 변수명...) 
	//구현부
    int result= a+b;
    return result;
}
public class Math {
    int add(int a, int b){return a+b;}
    int minus(int a,int b){return a-b;}
}
class MathTest{
    public static void main(String[] args) {
        Math mm=new Math();
        int result = mm.add(3,5);
        int result2 = mm.minus(9,4);

        System.out.println("add: "+result);
        System.out.println("minus: "+result2);
    }
}

출력결과

add: 8
minus: 5 
  • 재귀호출
    1.메서드의 내부에서 자기자신을 호출하는 것
    2.조건문 필수
    3.반복문보다 수행시간이 더 걸리지만 논리적 간결함이 필요할때 사용됨(ex.팩토리얼)
public class Factorial {
   public static void main(String[] args) {
       int result=fac(4);
       System.out.println("F(4)="+result);
   }
   static int fac(int n){
       if(n==1){
           return 1;
       }
       return  n*fac(n-1);//메서드 fac()를 다시 호출함
   }
}

출력결과

F(4)=24
  • 클래스 메서드와 인스턴스 메서드
    클래스멤버
    가 인스턴스 멤버를 참조, 호출하고자 하는 경우에는 인스턴스를 생성해야함
public class Math {
    int a,b;
    //인스턴스
    int add(){return a+b;}
    int minus(){return a-b;}
	//클래스
    static int add(int a,int b){return a+b;}
    static int minus(int a,int b){return a-b;}
}
class MathTest{
    public static void main(String[] args) {
    	//인스턴스메서드, 객체 생성 후에 호출 가능
        Math mm=new Math();
        mm.a=8;
        mm.b=3;
        System.out.println(mm.add());
        System.out.println(mm.minus());
		//클래스메서드, 인스턴스 생성없이 호출 가능
        System.out.println(Math.add(8,3));
        System.out.println(Math.minus(8,3));
    }
}

출력결과

11
5
11
5
profile
초보 개발자

0개의 댓글