클래스 : 객체를 정의한 것
객체 : 실제로 존재하는 것
ex)
클래스 객체 제품 설계도 제품 TV설계도 TV 붕어빵 기계 붕어빵
인스턴스 : 클래스로부터 만들어진 객체
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) 입니다.
//선언부 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
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