본문 바로가기

공부/컴공

자바 공부

선언시 구조
public class 클래스명(이것은 파일이름과 동일해야함)      {
public static void main (String [] args) {
프로그램 내용
}
}

//////////////
System.out.println()  - printf의 기능
System.out.println(변수명)  - 이런식으로도 출력가능

** println 은 선언후 바로 \n 가 사용되지만 생략되잇는 경우임
** print 는 C에서의 printf와 그냥 동일


///////////////
여러개의 문자 선언시 
String 선언 사용


////////////////////
변수와 문자열의 조합 출력시

String 변수명1 = 변수명2 + "문자열";
System.out.println(변수명1);

EX)
String apple = "사과";
int a = 3;
String fruit = apple + "는" + a + "개";
System.out.println(fruit);

********************************
System.out.println("문자열" + 변수명);

그냥 이런식으로도 출력 가능



///////////////////////
배열 선언시
int [] [] a = {
     { 10, 20, 30 },
     { 40, 50 },
     { 60 }
};

[] 가 앞에 옴

-----------------------
그냥 선언만 할경우
int [] [] a = new int [3] [];
a[0] = new int [3];
a[1] = new int [2];
a[2] = new int [1];



/////////////////////////
연산자
print에서의 연산자 사용시 '+', '-' 는 괄호안에 넣어서 한다.

System.out.println("5+5는 " + (5+5) + "입니다.");
System.outprintln(5X5는 " + 5*5 + "입니다.);



//////////////////////////////
객체지향 개념
- 클래스 : 클래스 안에 여러가지 필드(변수)가 정의되는 것이다
- 오브젝트 : 클래스에서 사전에 정의한 필드들에 새로 정의한 오브젝트 안에다가 값을 대입시켜주는 것이다
이것은 쉽게 생각하자면 C언의 사용자 함수에서 발전된 형태라고도 할수 있겠다.




////////////////////////////////
오버로딩 개념
아마 C언어에서도 있는 개념인것으로 기억함
- 하나의 클래스 내에 이름은 같으나 인수의 개수나 형이 다른 형태의 메소드(사용자 함수)를 여러개 정의하는 것이다

class Calc {
int add(int a, int b){
return a + b;
}

int add(int a){
return a + 1;
}
}

위의 형태 처럼 선언할 경우에는 메소드 호출시 인수의 형태에 따라 다른 함수가 호출된다.



/////////////////////////////////
생성자
오브젝트 생성시에 자동적으로 호출되는 특수한 메소드이다. (클래스 정의할 때 정의해준다.)

class B{
int s, t;
B(int a, int b){                     < -- 클래스와 같은 이름
s = a;
t = b;
}
}

class TestB{
B b = new B(3, 4);
...
...
}



///////////////////////////////
복제 생성자
생성자를 통해 필드에 입력된 값을 복제 생성자로 정의된 필드에 값을 대입시켜주는 것이다.

class Book{
String title;
String writer;
Book(String t, String w){
title = t;
writer = w;
}
Book(Book copy){
title = copy.title ;
writer = copy.writer;
}
void print(){
System.out.println("제 목 : " + title);
System.out.println("저 자: " + writer);
}
}

class Books{
public static void main(String [] args){
Book book1 = new Book("C가 보이는 그림책", "ANK");
book1.print();
Book book2 = new Book(book1);
book2.title = "Java가 보이는 그램칙";
book2.print();
}
}





///////////////////////////////////////
상속의 개념
- 슈퍼 클래스의 필드를 그대로 서브 클래스에게 상속 시켜주는 것이다
ex) class Cat extends Animal
          클래스명             슈퍼 클래스명

소스

class Book{
String title;
String genre;
void printBook(){
System.out.println("제 목 : " + title);
System.out.println("장 르 : " + genre);
}
}

class Novel extends Book{
String writer;
void printNov(){
printBook();
System.out.println("저자 : " + writer);
}
}

class Magazine extends Book{
int day;
void printMag(){
printBook();
System.out.println("발매일: " + day + "일");
}
}

class Bookshelf{
public static void main(String [] args){
Novel nov = new Novel();
nov.title = "구운몽";
nov.genre = "고전문학";
nov.writer = "김만중";
Magazine mag = new Magazine();
mag.title = "월간 자바 그림책";
mag.genre = "컴퓨터";
mag.day = 20;
nov.printNov();
System.out.println();
mag.printMag();
}
}



//////////////////////////////
Private 접근 제한자
private 으로 선언하면 다른 클래스에서 참조할 수는 없다.
그러나 private필드를 사용한 메소드는 여전히 사용 가능하다.


class Person{
private String name;
void setName(String n){
name = n;
}
String getName(){
return name;
}
}

class Girl extends Person{
void print(){
System.out.println(getName() + "양");
}
}

class TestPerson{
public static void main(String [] args){
Girl nara = new Girl();
nara.setName("나라");
nara.print();
}
}



////////////////////////////////////////////////
슈퍼클래스와 서브 클래스에서의 오버 라이딩

서브클래스와 슈퍼클래스에서 동일한 이름의 메소드가 존재할수 있다.
또한 서브 클래스에서 super.메소드 로 지정시 슈퍼 클래스의 메소드가 실행된다.



//////////////////////////////////////////////////
final 과 static 제한자

final은 필드나 클래스에 붙일수 있다.
final int a=3;                          final class Animal {           }
이럴 경우에는 필드는 값을 변경할 수 없고 클래스는 상속할 수 없게 된다.




////////////////////////////////////////
추상 클래스와 메소드
자세한 것은 기술하지 않고 호출하는 방법만 정의 해놓는것을 추상 메소드라고 한다
* 추상 클래스나 인터페이스를 상속받는 클래스 생성시 추상 메소드를 반드시 포함 시켜야만 하기 때문에
프로그래밍시 실수로 빼놓는 일이 없어진다.


abstract class Calc1{
int a;
int b;
abstract void answer();
void setData(int m, int n){
a = m;
b = n;
}
}

class Plus extends Calc1{
void answer(){
System.out.println(a + " + " + b + " = " + (a + b) );
}
}

class Calculation1{
public static void main(String [] args){
Plus plus = new Plus();
plus.setData(27, 32);
plus.answer();
}
}


////////////////////////////////////////////////////
instanceof 명령어

오브젝트가 지정한 클래스의 하위 오브젝트인지 조사하기 위한 연산자이다.

boolean flat = c instanceof x;
           오브젝트명        클래스명

interface Cry{
void cry();
}

class Cat{
public void cry(){
System.out.println("야옹~");
}
}

class Dog implements Cry{
public void cry(){
System.out.println("멍멍");
}
}

class checkCry{
public static void main(String [] args){
Cat cat = new Cat();
Dog dog = new Dog();
if(cat instanceof Cry){
cat.cry();
}
else if (dog instanceof Cry){
dog.cry();
}
}
}


//////////////////////////////////////////
인터페이스를 임플리먼트시 메소드를 public 으로 선언해야한다.

슈퍼클래스의 서브 클래스 생성시 다음과 같이도 생성이 가능하다
X a = new Y();

X= 슈퍼클래스, Y = 서브 클래스

이는 서브 클래스 생성과 같다.


////////////////////////////////////////////
파일 입출력
파일 입출력 다룰 시에는 import java.io.*; 가 필요
* 예외 처리도 해야함
try / catch / finally
try - 기본적인 처리
catch - 예외가 발생시 수행할 처리
finally - 예외가 일어나던 안일어나던 그냥 실행시키기

- 문자열(16비트) 읽고 쓰기
FileReader in new FileReader("file1.txt");  // 문자열 읽기
FileWriter out = new FileWriter("file2.txt");  // 문자열 쓰기

- 바이너리(8비트) 읽고 쓰기
FileInputStream in = new FileInputStream("file3.dat");  // 바이너리 읽기
FileOutputStream out = new FileOutputStream("file4.dat");  // 바이너리 쓰기

* 바이너리 입력을 문자 입력으로 변환하기
FileInputStream ifile = new FileInputStream("file5.dat");  // 바이너리 읽기
InputStreamReader in = new InputStreamReader(ifile);  // 바이너리를 문자열로 변환 시켜주기
*빨간색 글씨는 오브젝트명이므로 임의로 정해도 됨

** 파일 읽기의 절차
1. 위의 선언으로 파일을 연다.
2. 데이터를 읽어 온다. ( int c; c = in.read();  )
3. 파일을 닫는다 ( in.close(); )


EX)
import java.io.*;
class InOut{
public static void main(String [] args){
try{
String filename = "file.dat";
FileOutputStream out = new FileOutputStream(filename);
FileInputStream file = new FileInputStream(filename);
InputStreamReader in = new InputStreamReader(file);
for(byte i = 1; i<= 10; i++){
out.write(i);
}
int c;
while((c=in.read()) != -1){
System.out.print(c + " ");
}
in.close();
out.close();
} catch(IOException e){
System.out.println("파일 없뜸");
}
}
}


//////////////////////////////////////
키보드 입력
- 반각 문자 하나 받기 위해서는 read() 메소드 사용
int a;       a = system.in.read();

- 한줄 전체를 입력 받기 위해서는 BufferedReader 클래스 사용
InputStreamReader a = new inputStreamReader(system.in);
BufferedReader = new BufferedReader(a);

EX)
import java.io.*;
class NumberGame{
public static void main(String [] args){
try{
BufferedReader in = 
new BufferedReader(new InputStreamReader(System.in));
int a, b = (int)(Math.random() * 10);
System.out.println("이름은?");
String name = in.readLine();
System.out.println("0에서 9 입력");
String c = in.readLine();
a = Integer.parseInt(c);
while(a!=b){
if(( a == b-1) || (a == b+1))
System.out.println("아까움");
else if( a > b+1)
System.out.println("작은 수임");
else if ( a < b-1)
System.out.println("큰 수임");
c = in.readLine();
a = Integer.parseInt(c);
}
System.out.println("정답 " + name + "님 ㅊㅋ");
} catch(IOException ie){
System.out.println("에러");
}
}
}



'공부 > 컴공' 카테고리의 다른 글

그래픽스  (0) 2010.03.16