금요일, 3월 29
Shadow

#011 JAVA 클래스 구조

*중요
6.1 클래스의 일반 구조
클래스는 객체를 생성하는 template
자바 프로그램은 클래스의 집합
클래스는 크게 2개의 요소로 구성
-객체가 가질수 있는데이터속성(데이터를 포함 할수도 있음)
-데이터를 조작할수 있는 메소드
6.1 클래스의 구성
<클래스-클래스헤더,[클래스맴버>-(맴버변수,생성자,메소드)]

class Class-name{//클래스 헤더부분
type1 varName1=value1; //맴버변수
typeN varNameN=valueN;//맴버변수

Class-name(arg1){//생성되는 객체의 초기과정기술(생성자))
}

mtype Mname1(margs1){//메소드기술(메소드)
}
}

맴버변수는 Class밖에 선언한 변수
생성자는  Class변수와 이름이 같은 메소드(여러개 나올수 있음 argment가 다르게)

class SampleClass{//클래스 헤더부분
int a;  //맴버변수 부분
int b;
int c;

public SampleClass(int x,y,z){//생성자 부분. 이름이 클래스 명과같다.
a=x;
b=y;
c=z;
}
public int sum(){//메소드 부분
int d;
d=a+b+c;
reutrn d;
}
}
6.2클래스 선언
[public/final/abstract] class Class-name{//클래스 헤더 부분
//클래스 맴버부분
}

클래스 생성시 클래스의 성격을 지정하는 한정자 사용

public : public은 다른 어던 클래스 에서도 이 클래스를 사용(클래스의 객체를 생성하는것) 할 수 있음을 의미, 한정자를 지정하지 않으면 같은 패키지내의 클래스들만 접근 가능
final : final은 서브 클래스를 가질수 없는 클래스
abstract : 추상 메소드를 가지는 추상(abstract) 클래스 의미

public class Box{
int width;
int height; //데이터의 속성만 선언된 클래스
int depth;
}

public class Box{
int width;
int height;//데이터의 속성과 메소드를 가진 클래스
int depth;
public void volum(){//메소드
int vol;
vol=width * height * depth;
System.out.println(“Volume is ” + vol);
}}
class Box{
int width;
int height;//데이터의 속성과 생성자 메소드를 가진 클래스
int depth;
public void Box(int w, int h, int d){ //생성자, 클래스 명과 이름이 같다.
width =w;
height=h;
depth=d;
}
public void volume(){//메소드
int vol;
vol=width * height * depth;
System.out.print(“Volume is ” + vol);
}
}
}

6.3 객체의 생성
-객체의 선언
–클래스명 객체참조변수;
-객체의 생성
–객체의 참조변수 =new 클래스명();
-객체의 선언과 생성
–클래스명 객체참조변수 == new 클래스명();

class Box{
int width;
int height;
int depth;
}
class Mybox{
Box mybox1;
Box mybox2;
mybox1 = new box(); //또는 box mybox1= new Box();
mybox2 = new box(); //또는 box mybox2= new Box();
}

객체의 선언과 생성
객체의 선언 : 객체의 선언은 null 값을 가진 변수만을 의미
box mybox1; //null
box mybox2; //null
————————–
객체의 생성 : 객체에 대한 메모리가 할당되고 변수(객체참조변수)는 객체에 대한 참조(주소)를 가진다.

mybox1 new Box(); mytbox1=width,height,depth
mybox2 new Box(); mytbox2=width,height,depth

TwoBox.java
class Box{
int width;
int height;
int depth;
}

Class TwoBox{
public static void main(String args[]){
box mybox1=new box();
box mybox2=new box();
int vol1,vol2;

//첫번째 박스 객체 생성부
mybox1.width=20;
mybox1.height=40;
mybox1.depth=15;

//두번째 박스 객체 생성부
mybox2.width=10;
mybox2.height=20;
mybox2.depth=30;

vol1= mybox1.widht* mybox1.height * mybox1.depth;
system.out.println(“첫번째 박스의 부피는” + vol1 + “입니다.”);

vol2= mybox2.widht* mybox2.height * mybox2.depth;
system.out.println(“두번째 박스의 부피는” + vol2 + “입니다.”);
}
}

————————
6.4 맴버변수

-맴버변수는 클래스 내의 메소드 밖에 선언된 모든것을 의밓ㅏㄴ다.
-맴버변수는 객체가 가질수 있는 속성들을 나타낸다
-맴버변수-[클래스변수,종단변수,객체변수[객체속성변수,객체참조변수]]
맴버변수 선언
[public/private/protected][static/final]변수형 변수명;

static : 클래스변수, final : 종단변수
static 과 final이 붙지 않은 변수 : 객체변수(객체속성변수 또는 객체참조변수)
접근 한정자 public/private/protected
객체 변수: 객체가 가질수 있는 특성을 표현
-객체속성변수 :  객체가 가질수 있는 속성을 나타내는 값으로서 기본자료형의 값들로 구성
-객체참조변수 : 객체를 지정하는 변수. 자바에서는 기본자료형을 제외한 모든 요소들을 객체로 취급
-사용자는 객체를 생성한 다음 그 객체에 접근하기 위해서는 객체 참조변수를 통하여 그 객체의 맴버들에 접근할수 있다.
class Box{
int width; //객체 속성변수 width
int height;//객체 속성변수 height
int depth;//객체 속성변수 depth
}
class Mybox{
int vol;//객체 속성 변수 vol
Box mybox1;//객체참조변수 mybox1
Box mybox2;//객체참조변수 mybox2
String boxname;//객체참조변수 boxname //자바에서 문자열은 객체로 취급한다.
mybox1=new box();
mybox2=new box();
}}

int my_count1=100;
int my_count2=my_count1;
Box mybox1=new Box();
Box mybox2=mybox1;

//객체속성변수 : 변ㅅ의 값이 복사되어 전달
int my_count1=100;
int my_count2=my_count1; //call by value
//객체참조변수 : 객체에 대한 주소가 전달되어 결국 같은 객체를 가르키게 된다.
Box mybox1=new Box();
Box mybox2=mybox1;
//call by refrense

buy.java
class Fruit{
int apple=5; //객체속성변수
int straw=10;
int grapers=15;
}

class Buy {
public static void main(String args[]){
int quantity1, quantity2;

Fruit f1= new Fruit();
Fruit f2=f1;
quantity1=f1.apple+f1.straw+f1.grapes;
quantity2=f2.apple+f2.straw+f2.grapes;
System.out.println(“객체 f1의 초기 과일 개수 ” + quantity1+”개”);
System.out.println(“객체 f2의 초기 과일 개수 ” + quantity2+”개”);
f1.apple=10;
f2.straw=20;
f1.grapes=30;
quantity1 =f1.apple + f1.straw + f1.grapes;
quantity2=f2.apple + f2.straw + f2.grapes;
System.out.println(“객체 f1의 변동후 과일 개수 ” + quantity2+”개”);
System.out.println(“객체 f2의 변동후 과일 개수 ” + quantity2+”개”);
}
}

———————–
-클래스변수
클래스 변수: static 을 붙여 선언한다.
클래스변수는 전역변수의 개념을 가진다.

-클래스변수의 용도
-객체변수(객체참조, 객체속성)는 객체가 생성될때마다 각 객체에 변수들이 생성되지만, 클래스 변수는 클래스로 부터 생성된 객체들의 수와 상관없이 하나만 생성
-한 클래스로 부터 생성된 모든 객체들은 클래스 변수를 공유
-클래스변수를 이용하여 객체들 사이의 통신에 사용하거나 객체들의 공통 속성을 나타낼수 있다.
-객체변수와는 달리 클래스 변수는 클래스 이름을 통하여 접근

클래스는 Test(클래스)로 부터 생성된 모든 객체들은 test.numver로 클래스 변수에 접근할수 있다.

class Box{
int width;
int height;
int depth;
long IDNum;
static long boxID=0; //클래스 변수선언
public Box()
idNUm=boxID++;
//생성자가 수행될떄마다 클래스변수의 값을 증가
}
}
*Bxo클래스로 부터 생성되는 모든 객체의 idNum 값은 객체가 생성되는 순서에 따라 유일한 값을 가지게된다.
class Box{
int width;
int height;
int depth;
long IDNum;
static long boxID=0; //클래스 변수선언
public Box()
idNUm=boxID++;
}
}
class Static Demo{
public static void main(String args[]){
Box mybox1=new Box();
Box mybox2=new Box();
Box mybox3=new Box();
Box mybox4=new Box();
System.out.println(“mybox1= ID 번호 : ” + mybox1.idnum);
System.out.println(“mybox2= ID 번호 : ” + mybox2.idnum);
System.out.println(“mybox3= ID 번호 : ” + mybox3.idnum);
System.out.println(“mybox4= ID 번호 : ” + mybox4.idnum);
System.out.println(“전체박스의 개수는 ” + Box.boxID+ “입니다.”);
}
}

———————–
맴버변수 -종단변수(final)
final int Max=100;
final int Min=1;

-예약어 final을 사용하여 종단 변수 지정
-변할수 없는 상수 값을 나타낸다.
-종단변수는 관례성 대문자로 표기한다.
-클래스 변수와 객체 속성변수를 접근하기 위해서는.을 사용
클래스 변수 : 클래스이름.클래스변수
객체속성변수: 객체이름.객체속성변수

Class A {
int aa;
int bb;
int cc;
static int s=0;

class ATest{
public static void main(String args[]){
A obja = new A();
obja.aa =4;//객체 참조변수에 접근
obja.bb=obja.aa *2;//객체 참조변수에 접근
obja.cc = a.s;//객체참조변수에 클래스 변수값 저장
}
}

6.5 맴버변수 접근 한정자
-자바는 객체지향의 특성인 캡술화(endcapsulation)와 정보 은폐(infomation hiding)를 제공하기 위해 맴버변수에 한정자를 사용
-맴버변수 한정자로 public private protected를 제공
-접근 한정자가 없는 맴버변수는 동일한 패키지와 하위 클래스에서 사용이 가능(public과 유사)

public 으로 선언된 객체 변수는 소속된 클래스가 접근가능하면 항상 접근 가능
class Box {
public int width;
public int height;
public int depth;
public long idNum; //속성변수
static long boxID =0;//클래스 변수
public box() { //생성자
idNum=boxID++;
}
}
class publicDemo{
public static void main(String args[]){
Box mybox1 =new Box();
mybox1.width=7; //접근가능
mybox2.Depth=20;
}
}
————————————-
class Box {
private int width; //private로 선언 이 클래스 내부에서만 사용
private int height;
private int depth;
private long idNum; //속성변수
static long boxID =0;//클래스 변수
private box() { //생성자
idNum=boxID++;
}
}
class publicDemo{
public static void main(String args[]){
Box mybox1 =new Box(10,20,30);
mybox1.width=7; //에러발생
mybox2.Depth=20;
}
}

protected로 선언된 객체 변수는 소속된 클래스의 하위 클래스와 소속된 클래스와 같은 패키지의 클래스에서만 사용가능
class Box{

private int width;
private int height;
private int depth;
protected int count; //이 클래스와 이 클래스의 하위클래스에서 사용가능
class ProtectedDemo1 extends Box{
//extends를 이용하여 Box 클래스의 하위 클래스로 생성
public static void main(String args[]){
Box mybox2=new Box();
mybox2.count =7;//접근가능
6.6 변수의 유효범위
유효범위를 기준으로 변수를 구분하면
-맴버변수
-메소드 매개변수와 지역변수
-예외처리기 매개변수
class Myclass{

public void aMethed(메소드매개변수){
메소드 지역변수들

catch(예외처리기 매벼변수){

}(예외처리기 매개변수의 유효범위)
}(메소드 매개변수와 메소드 지역변수의 유효범위)

}(맴버변수의 유효범위(모든메소드에서 사용가능)
——————
6.7 생성자(constructor)
-생성자는 클래스로 부터 객체가 생성될때 초기화 과정을 기술흔 ㄴ특수한 메소드
-생성자의 이름은 클래스 이름과 같다.
-생성자는 객체가 생성될때 자동으로 한번만 수행
-접근한정자의 의미는 맴버변수의 접근 한정자와 같다
-단 생성자가 private로 선언되는 경우는 클래스 내부에서만 사용한다는 의미이다.

public/protectd/private 클래스 이름(메개변수){
……….//초기화문장들
}

class Box{
private int width; //변수를 private로 선언하여 외부에서 접근을 막는다.
private int height; // 정보의 은폐제공
private int depth;
private int vol;
public Box(int a,int b,int c){ //클래스의 이름과 같은 이름으로 ㅅㅐㅇ성자 선언
width=a; //초기화작업수행
height=b;
depth=c;
}
public int volume(){
vol=width*height*depth;
return vol;
}
}
class BoxTestDemo{
public static void main(String args[]){
int vol;
box mybox1= new Box(10,20,30);
vol =mybox1.volume();
System.out.println(“mybox1객체의 부피:” + vol);
}
}
—————————
6.8 생성자 오버로딩(overloading)
-클래스에 하나 이상의 생성자를 중첩하여 사용할수 있다.
-여러개의 생성자를 사용할때는 생성자의 이름같지만 매개변수의 타입과 개수는 달라야한다.

class Box{
int width;
int height;
int depth;
PUblic Box(){
width=1;
height=1;
depth=1;
}

public Box(int w){
width=w;
height=1;
depth=1;
}
public Box(int w,int h){
width=w;
height=h;
depth=1;
}
public BOx(int 2,int h,int d){
width =2;
height=h;
depth=d;
}
//4개의 생성자가 서로 다른 매개변수를 가진다.
Box mybox1=new Box();
Box mybox2=new Box(5);
Box mybox3=new Box(5,10);
Box mybox4=new Box(5,10,15);

class Box(
int width, height,depth;
double dwidth,dheight,ddepth;
public Box(int w,int h,int d){
width =w;
height =h;
depth=d;
}
public (double w, double h, double d){
dwidth=w;
dheight=h;
ddepth=d;
}
}
//매개변수의 개수는 같지만 타입이 다른경우
Box mybox5 =new Box(5,10,15);
box mybox6 =new Box(20.3,10.7,15.23);
6.9 예약어 this
-this 는 현재의 객체를 의미
-생성자나 메소드의 매개변수와 객체 변수가 같은 이름을 가질때 사용
-같은 클래스내의 다른 생성자를 호출할 떄 사용
class Box{
int widht;//객체속성변수는 생성자 매개변수와 같은 의미
int height;
int depth;
public void Box(int widht; int height, int depth){
width=width; //같은변수(생성자 매개변수의 값을 배정
height=height;
depth=depth;
}
}

//문제가 생김

 

class Box{
int width;
int height;
int depth;
public Box(int width, int height, int depth){
this.width=width;
this.height =height;
this.depth=depth;

this.width는 현재 객체의 객체 속성 변수 width를 의미.
this를 사용함으로서 같은 이름을 객체변수와 생성자 매개변수의 이름으로 사용할수 있다.

this는 위의 맴버변수

class Box{
int width;
int height;
int depth;
public Box(){
this(1,1,1);
}
public box(int w){
this(w,1,1);  //w,1,1을 맨 밑의 값에  호출
public Box(int w,int h){
this(w,h,1);
}
public Box(int w,int h,int d){
widht=w;
height=h;
depth=d;
}
//이 클래스는 어떠한 형태로 객체가 생성되어도 결국 마지막 생성자가 호출된다. 여기서 사용된 this는 같은 클래스 내의 다른 생성자를 호출하는 역할을 한다.

6.10 메소드
-매소드
-객체가 할 수 있는 행동을 정의
-메소드의 이름은 소문자로 시작하는 것이 관례
[접근한정자] [static/final/abstract/synchronized] 반환값 메소드 이름([매개변수들])
{
………..//지역변수선언및 메소드행위기술
}

-접근한정자 public/private/protected는 맴버변수 접근한정자와 같은 의미

Method Demo1.java
class Frult{
int apple;
int straw;
int grapes;
int sum;
Fruit(int apple, int straw, int grapes){
this.apple=apple;
this.straw=straw;
this.grapes=grapes;
}
public int count(){
sum=apple + straw + grapes;
return sum;
}
}

class MethodDemo1{
public static void main(String args[]){
Fruit F1 =new Fruit(30,30,30);
total =f1.count();
System.out.println(“객체 f1의 총 개수 =” + total);
System.out.println(“객체 f1의 apple개수 = ” + total);
//사과의 개수를 읽어 오기 휘새 객체 속성 변수에 직접접근
//객체 속성 변수의 값을 직접변경(f1.apple=90;)할 수도 있다.
System.out.println(“객체f1의 straw 개수= ” + f1.straw);
System.out.println(“객체 f1의 grapes 개수 =” + f1.grapes);
}
}
———————-좋지않은 프로그램
class Fruit{
private int a;
private int s;
private int g;
private int sum;
Fruit(int apple,int straw, int grapes){
a=apple;
s=straw;
g=grapes;
this.count();
}
private void count() { //count()라는 메소드를 숨긴다.
sum =a+s+g;
}
public int gettotal(){
//모든 과일의 합은 이 메소드를 통해서만 접근
return sum;
}

public int getapple(){
//a 값에 대해 읽기만 허용하기 위한 메소드
retrun a;
}

public int getstraw(){
retrun s;
}

public int getgrapes(){
return g;
}
}

class MethoDemo2{
public static void main(String args[]){

int total;
Fruit f1=new Fruit(30,30,30);
total =f1.gettotal(); //f1.count()를 사용하면 에러 발생
System.out.println(“객체 f1의 총 개수 =” + total);
System.out.println(“객체 f1의 apple 개수= + ” f1.getapple());
//메소드를 이용하여 사과의 개수를 읽어 오는것만 가능하다.
//만일 사용자가 “f1.a=50;”과 같은 문장으로 객체 속성 변수에 직접 접근하려 한다면 에러가 발생한다.
System.out.println(“객체 f1의 straw 개수= + ” f1.getstraw());
System.out.println(“객체 f1의 grapes 개수= + ” f1.getagrapes());
}

————-클래스메소드:static
-static 을 붙여 클래스 매소드 선언
-클래스 변수와 같이 클래스 명을 통하여 접근
-클래스 메소드 내에서는 클래스 변수만 사용할수 있다.

ex>
class Box {
int width;
int height;
int depth;
long idNum;
static long boxID=100;
static long getcurrentID(){ //클래스 메소드는 클래스 변수만 사용
return boxID++
}
}

class static methodDemo{
public static void main(String args[]){
Box mybox1 = new Box();
mybox1.idNum =Box.getcurrentID(); //클래스 명을 통해 메소드 사용
Box mybox2=new Box();
mybox2.id num box.getcurrentID();
System.out.println(“mybox1의 ID번호 : ” + mybox1.idNum);
System.out.println(“mybox2의 ID번호 : ” + mybox2.idNum);
System.out.println(“다음 박스의 번호는 ” + Box.boxID + “번 입니다. “);
}
}

final: final로 선언된 메소드는 하위클래스에서 overriding(치환) 될수 없는 메소드이다.
abstract: 추상 메소드로서 추상 클래스내에 선어될수 있다.
synchronized: 쓰레드 동기화를 위한 메소드

메소드 접근
-일반 메소드와 클래스 메소드에 접근

클래스 메소드 접근형식 :  클래스이름.클래스메소드이름(매개변수)
일반 메소드 접근방식 : 객체이름.객체메소드이름(매개변수)

——————-메소드반환값
메소드 선언부에 반환값이 지정되어야 한다.
반환값이 없을경우 void로 지정
기본 자료형 뿐만아니라 참조자료형의 데이터도 반환
public int sum(int a, int b){ //메소드 선언
int c=a+b;
return c;
}
//기본 자료형 데이터를 반환하는 메소드, 메소선언부에 지정된 반환 타입과 실제반환하는 데이ㅐ터 타이입이 일치해야한다.

public Box volume compute(Box instance_box){
Box v_box=Box();
v_box.width=instance_box.width;
v_box.height=instance_box.height;
v_box.depth=instance_box.depth;
v_box.volume=v_box.width *v_box.height *v_box.depth;
return v_box;
}
//참조 자료현인 객체를 반환하는 메소드

 

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

이 사이트는 스팸을 줄이는 아키스밋을 사용합니다. 댓글이 어떻게 처리되는지 알아보십시오.