노력과 삽질 퇴적물

JAVA: 자바 기초 (2) 본문

프로그래밍note/언어. JAVA & JDK 계열

JAVA: 자바 기초 (2)

MTG 2012. 7. 11. 16:18

JAVA: 자바 기초 (1)

JAVA: 자바 기초 (2)

JAVA: 자바 기초 (3)

JAVA: 자바 기초 (4)






05장. 함수(매소드or 메서드)

 1. 함수 구조 및 기본사용


//package chapter05;

import java.io.IOException;

import java.io.BufferedReader;

import java.io.InputStreamReader;


public class Exam40

{

public static void main( String[] message ) throws IOException

{

input();//입력처리 함수를 호출하므로 메인에도 'throws IOException'를 붙인다

}


public static void input() throws IOException

{

BufferedReader key = new BufferedReader (new InputStreamReader(System.in));

System.out.print("블로그명 : ");

String name = key.readLine();

System.out.print("블로그주소 : ");

String url = key.readLine();

System.out.print("블로그개설 : ");

int year = Integer.parseInt(key.readLine());

System.out.print("'" + name + "'" + "는 " + year + "에 개설되었습니다\n" + url);

}

}




 2. 함수 유형별 사용법


//package chapter05;

public class Exam42

{

public static void main( String[] message ) // 함수 매개변수에 행렬도 가능.

{

int a = 3;

int b = 10;

System.out.print("JAVA_intermediate Skill\n");

exter_func01();      // void exter_func01()

exter_func02(2, 5); // void exter_func02( int mediation_x, int mediation_y )

exter_func02(a, b); // 함수 재호출 및 사용의 예시.

exter_func03(10, 30);// int exter_func03( int mediation_x, int mediation_y )

exter_func04();      // int exter_func04()

}


// 반환유형 및 return [X] 매개변수[x]

public static void exter_func01()

{

System.out.print("public static void external_func01()\n\n");

}

// 반환유형 및 return [X] 매개변수[O]

public static void exter_func02( int mediation_x, int mediation_y ) // 매개변수의 유효범위(scope) == 소속 함수내

{

System.out.print("public static void external_func02( int x, int y )\n");

System.out.print(x + "\t" + y + "\n");

}

// 반환유형 및 return [O] 매개변수[O]

public static int exter_func03( int mediation_x, int mediation_y )

{

System.out.print("public static int external_func03( int x, int y )\n");

int sum = x + y;

System.out.print("sum = x + y = " + sum + "\n\n");

return sum;

}

// 반환유형 및 return [O] 매개변수[x]

public static int exter_func04()

{

System.out.print("public static int external_func04()\n");

//int internal_num;

int sum = 2000 + 12;

System.out.print(" sum = " + sum + "\n");

return sum;

}

}






06장. 클래스

* 객체 생성 = 인스턴스 생성

 1. 클래스 기본 구조 및 사용법


//package chapter06;

class People // 클래스명 첫글자는 대문자

{

public int x;

public int y;

//접근지정자 클래스명 클래스태그명;

}


public class Exam53

{

public static void main( String[] message )

{

// new를 통해 인스턴스(객체) 생성.

People person1 = new People(); // 객체명은 클래스명을 따올것을 권장.

People person2 = new People();

person1.x = 50;

person1.y = 60;

System.out.print("class People person1\n"

+ "x : " + person1.x + "\n"

+ "y : " + person1.y + "\n\n");

person2.x = 77;

person2.y = 88;

System.out.print("class People person2\n"

+ "x : " + person2.x + "\n"

+ "y : " + person2.y + "\n");

}

}




* 클래스명 => 생성자명()

 2. 데이터 접근법

-> 점연산자[.]를 이용한 접근법

-> 함수를 이용한 접근법

-> 생성자를 이용한 접근법

//package chapter06;

class Test02

{

public int class_mem1;

public int class_mem2;

public Test02()

{

}

public Test02(int x, int y) //생성자도 다형성적용가능

{

this.class_mem1 = x;

this.class_mem2 = x + 2012;

}

public void getX(int x, int y)

{

this.class_mem1 = x;

this.class_mem2 = y;

}

public void print()

{

System.out.print("x = "  + class_mem1 + "\t"

+"y = " + class_mem2 + "\n\n");

}

}


public class Exam64

{

public static void main( String[] message )

{

// 점연산자를 이용한 접근 : 클래스 필드멤버에 직접 접근

Test02 t1 = new Test02();

t1.class_mem1 = 2000;

t1.class_mem2 = 12;

t1.print();

// 함수를 이용한 접근 : 클래스내 값을 처리하는 함수 별도로 구현

Test02 t2 = new Test02();// 함수를 이용한 접근 예시용.

t2.getX(1, 2);

t2.print();

// 생성자를 이용한 접근 : 객체생성시 값을 입력.

Test02 t3 = new Test02(3, 4);// 생성자를 이용한 접근 예시용.

t3.print();

}

}




 3. this/super

-> this : 클래스내 전역변수임을 표기(C++로 치면 ::x로 전역변수인걸 표기)

-> super : 조상클래스(상위클래스)를 상속받은 후손클래스(하위클래스)내에서 조상클래스 멤버와 후손클래스 멤버를 구별하기 위한 참조변수. '07. 객체 지향 프로그래밍'의 '2. 상속'도 충분히 이해해야 합니다.

//package chapter06;

class Parent // Higher Level CLASS

{

protected int x;

protected int y;

public Parent(int x, int y)

{

this.x = x;

this.y = y;

}

}


class Childern extends Parent // Lower Level CLASS

{

private int x;

private int y;


public Childern(int x, int y)

{

super(x, y);

this.x = x + 2;

this.y = y + 2;

}


public void print()

{

System.out.print("super : " + super.x + "\t" + super.y + "\n");

System.out.print("this  : "   + this.x    + "\t" + this.y     + "\n");

}

}


public class Exam65

{

public static void main( String[] message )

{

Childern[] arr = new Childern[3];

arr[0] = new Childern(10, 20);

arr[1] = new Childern(50, 60);

arr[2] = new Childern(77, 88);

for( int i = 0; i < arr.length; i++ )

{

arr[i].print();

System.out.print("\n");

}

}

}




 4. static변수(클래스 변수)와 내부클래스

-> static변수(클래스 변수)는 모든 인스턴스(객체)에게 공용이다.

-> 참고자료, java :: InnerClass (내부클래스)‎

package chapter07;


class HighClass

{

private int x = 100;

private static int y = 200;

public void print()

{

System.out.print(x + "\t" + y);

}

// 정적인 중첩 클래스 = 필드에서 드물게 사용?

static class InnerClass

{

private int a = 10;

private static int b = 20;

public void print()

{

//System.out.print(x + "\t" + y); // 에러. private int

System.out.print("[InnerClass] private int a : " + a + "\n"

+ "[InnerClass] private int b : " + b + "\n"

+ "[HighClass]  private static int y : " + y );

}

}

}


public class Exam73

{

public static void main( String[] message )

{

HighClass.InnerClass obj = new HighClass.InnerClass();

obj.print();

}

}




 5. 익명클래스
-> 사용빈도가 적은 클래스를 써야할경우 가능한 방식.

-> 생성자의 매개인수에 객체타입으로 함수를 직접정의하는것이다.
-> 참고자료, 살아가는 이야기 :: Java 익명 클래스

 




 5. abstract

-> 추상클래스는 자신을 생성자로 받지 못하고, 자식클래스를 생성자로 받을수 있다.

     abstract class ParentAbstract

     class ChildAbstract extends ParentAbstract

     ...

     ParentAbstract pAbstract = new ParentAbstract();//에러

     ParentAbstract cAbstract = new ChildAbstract();//에러

-> 추상클래스내 추상 함수들이 있으면 상속받는 자식 클래스에서 해당 추상함수들이 코드상 필수적으로 기입된다.

 부모에게 있던 추상함수들은 자식클래스에서 재정의해서 사용.

-> https://wikidocs.net/219







07장. 객체지향 프로그래밍(OOP)

 1. 오버로드(or 오버로딩)

-> 함수명이 같더라도 반환타입/매개인수가 다르면 별개로 취급됨.

//package chapter07;


class Test3

{

private int _x;

private int _y;

public Test3() //오버로드 적용 생성자1

{

_x = 100;

_y = 200;

}

public Test3(int x, int y) //오버로드 적용 생성자2

{

this(); //생성자 끼리의 호출

this._y = y;

}

public void print() //오버로드 적용함수1

{

System.out.print("\t" + _x + "\t" + _y + "\n");

}

public void print(int x, int y) //오버로드 적용함수2

{

_x = x;

_y = y;

System.out.print("\t" + _x + "\t" + _y + "\n");

}

}



public class Exam67

{

public static void main( String[] message )

{

Test3 obj1 = new Test3();

Test3 obj2 = new Test3(50, 20);

Test3 obj3 = new Test3(11, 22);

System.out.print("오버로드를 적용한 생성자\n");

obj1.print();

obj2.print();

System.out.print("오버로드를 적용한 함수\n");

obj3.print();

obj3.print(333, 444);

}

}




 2. 상속

-> JAVA에서는 다중상속이 원칙적으로 불가. 하지만, 인터페이스를 통해 다중상속처럼 쓰는 방법은 있다.

-> 클래스가 인터페이스 상속은 받아도 인터페이스가 클래스를 상속받는건 없다.

-> JAVA에서 어떤 부모 클래스를 만들더라도 Object의 자식클래스가 된다. 즉, Object클래스가 시초클래스쯤 되고 코드상 생략일뿐이다.

//package chapter07;


class XX

{

public int x = 10;

public String str = "부모클래스 XX";

}


interface YY

{

public int y = 20; // final. 초기값 없으면 에러

public String str = "인터페이스 YY";

public void print();// abstract

}


class ZZ extends XX      //상속-부모클래스

      implements YY//상속-인터페이스. 이걸로 다중상속처럼은 가능.

{

public String str = "자식 클래스 ZZ";

public void sub()

{

x = 77;

}

public void print()

{

System.out.print(super.str + "\n"

       + str + "\n"//this.str로도 가능. 변수의 효력범위주의.

       + "x : " + x

      );

}

}


public class Exam83

{

public static void main( String[] message )

{

ZZ zzz = new ZZ();

zzz.print();

}

}




 3. 캡슐화 (은닉화)

-> public == 해수면밖 빙산

-> protected == 가문대대로의 비법(?)

-> private == 해수면속 빙산

//package chapter07;


class Parent

{

public String str;     //비상속관계 외부클래스 접근O   상속관계 자식클래스 접근O

public int x;

protected int y;       //비상속관계 외부클래스 접근X   상속관계 자식클래스 접근O

//private int y;//에러.//비상속관계 외부클래스 접근X   상속관계 자식클래스 접근X

}


class Child extends Parent

{

private int y;


public Child( String str, int x )

{

this.str = str;

super.x = x; // super는 부모클래스의 멤버변수에 접근시 사용.

y = 100; // this.y로도 가능. 변수의 효력범위를 잘 살펴볼것.

}

public Child( String str, int x, int y )

{

this.str = str;

super.x = x;

this.y = 100;

}

//클래스내 생성자 호출은 this();

public void print()

{

System.out.print(str + "클래스\n");

System.out.print("x : " + x + "\n"

+ "(Child) y : " + y + "\n"

+ "(Parent) y : " + super.y + "\n\n");

}

}


public class Exam77

{

public static void main( String[] message )

{

Child a = new Child("자식1", 10);

Child b = new Child("자식2", 77, 88);

a.print();

b.print();

}

}


'프로그래밍note > 언어. JAVA & JDK 계열' 카테고리의 다른 글

이클립스: 설정 및 팁  (0) 2012.07.20
JAVA: 자바 기초 (3)  (0) 2012.07.17
JAVA: 자바 기초 (1)  (0) 2012.06.07
안드로이드: 개발환경 구축  (0) 2011.11.23
JAVA: 간단한 RMI 테스트  (0) 2011.11.14