1. 객체지향의 주요 특성.
 1) 추상화 (Abstraction)
 2) 캡슐화 (Encapsulation)

 3) 상속화 (Inheritance)
  - 자바는 단일 상속으로 1개의 상위 클래스로부터 상속받을 수 있다. (역학 조사로 Maintanance에 좋지만 현실적으로 단일 상속을 사용하지 않는다. extends는 한번 사용하지만, 인터페이스(가상클래스)를 활용한다.)

 

C++ 

Java 

C# 

부모

 Base

Super 

base 

 표현

  :

 extends 

 

 자식

 Derived

 다중상속

 sub

단일상속

 

 

 
  - TwoD extends ThreeD : 생성자로 TwoD를 생성할때 먼저 부모클래스인 ThreeD를 메모리 heap에 올린다.
  - 자식 주소로 부모를 접근하면 상속, 부모 주소로 자식을 접근하면 다형성 이다.
  - class와 class, interface와 interface 간에는 extends, class와 inteface는 implements(동종간에는 extends,이종간에는 implements)
  - 관계    
    i) "is a"  : ex) 오토바이 -> 탈것
    ii) "has a"  ex) 주방 -> 냉장고
  - 상속이 되지 않는 것.
    i) private 선언 된 것은 상속되지않는다.
    ii) static 역시 상속되지 않는다.
    iii) 생성자는 상속되지 않는다.
       - 자식이 부모를 생성하려면 this메소드와 같은 형식의 super()를 사용한다. (마찬가지로 첫줄에 쓴다)
    iV) Overshadow 변수(클래스 변수와 같은 이름의 변수를 사용), Override 메소드 는 상속되지않는다. 자식 것을 쓴다.
       - super()를 사용하여 해결 할 수 있다.
       - String 형은 자체적으로 static 이기 때문에 this()나 super()이용해 접근할 수 없다.
 4) 다형성 (Polymorphism)

 
 
 
ps.----------------------------------------------------------------------------------------
- Object는 모든 객체들의 필수 요소의 집합이다. (원형이다.)
 
- 객체 비교에 대하여
   1. ==, !=
     1) value type -> 값비교, (su==num)
     2) Reference type -> 주소비교
     3) String type --> 값비교(new 없을 때), 주소비교(new 사용) //보통 String은 equals()를 사용한다.
   2. equals()
     1) value type --> 해당없음 (su.equals(num))
     2) Reference type --> 주소비교
     3) String type --> new와 관계없이 값비교
 

1. class

 1) 분류라는 의미의 Classification에서 왔다.

 2) Data와 Functions을 가지고있는 데이터 구조(Data structure)이다.


2. object

 1) 속성(property, state, attribute) : variable constants

 2) 행위(behavior) : method


3. 객체지향의 주요 특성.
 1) 추상화 (Abstraction) : 모델링 과정

 2) 캡슐화 (Encapsulation) : 중요한 부분을 외부로인한 접근과 변경으로부터 보호하기위함.
  - MS : Visibility(은닉)
  - Java : Accessibility(접근) : public / private
  - get/set : private 변수에 접근하기 위해 셋터와 겟터를 이용한다.
  - this : 멤버변수를 사용 (지역변수와 멤버변수명이 같을 때 멤버변수를 지칭하기위해 사용한다.)
 


 3) 상속화 (Inheritance)
 4) 다형성 (Polymorphism)

4. 생성자 : Allocating memory 
 1) 멤버 변수의 초기화는 생성자가 해야 한다.
 2) 특별한 메소드이다. : 기본적으로 생성자 메소드는 생략되어있다. : 
  - 리턴타입이 없다. 
  - 이름이 정해져있다(클래스이름)
  - new 와 함께만 사용할 수 있다.
 3) 정의 된 기본 생성자를 새로 정의 하는것 : 오버라이딩 (Overriding) 

public class ConstructorDemo2 {

public static void main(String[] args) {

Person1 p = new Person1("김태형", 27, 100.0);

Person1 p1 = new Person1("마이클", 28);

}

}

 public class Person1 {

private String name;

private int age;

private double salary;

public Person1(String name, int age, double salary){ // 기본 생성자의 오버라이딩.

this.name = name;

this.age = age;

this.salary = salary;

}

public Person1(String name, int age){ // 오버로딩

this.name = name;

this.age = age;

}

}

 기본 생성자의 경우는 오버라이딩(Overriding)과 오버로딩(Overloading) 모두 다 필요할 때가 있다.



4) this메소드

  - 생성자 내부에서 생성자를 호출 할 때 사용하는 것으로, this메소드는 생성자 안에서만 사용해야하며 블록의 첫줄에 써야한다.

 public class Person2 {

private String name;

private int age;

public Person2(){

//System.out.println("나 기본생성자.");

this("unknown",19);

}

public Person2(String name){this(name,19);}

public Person2(int age){this("unknown",age);}

public Person2(String name, int age){

this.name = name; this.age = age;

}

publi void main(String[] args){

Person2 p = new Person2();

}

}

 생성자 내에서 생성을 하면 또다른 주소가 생성되기 때문에 사용 할 수 없다. 그래서 this메소드를 사용한다.

ex)






ps.-------------------------------------------------------------
- main 함수가 없는 클래스는 스스로 단위 test(JUnit)를 통해 문제가 있는지 검사하게 된다. 
- 터미널에서 직접 컴파일을 할 경우 main 함수가 없는 클래스 부터 컴파일을 해야했지만 현재는 main함수가 포함된  클래스만 컴파일 해도 자동으로 모든 클래스 들을 컴파일을 해 준다.
- System.exit(-1);  //자바 프로그램 강제종료
- Java SE 에서 String Parsing 하는 방법 3가지
  1) String.split();
    - 
  2) java.util.StringTokienizer class
  3) Scanner class

 for (int i = 0; i < this.array.length; i++) {

String line = this.scan.nextLine().trim();

String [] array = line.split("\\s+");  //+는 1번 스페이스가 1개 이상이면 짜른다. ?는 0또는 1개, *는 0번 또는 1번이상(모두) 


'Programming > JAVA' 카테고리의 다른 글

자바 객체지향의 특징3 (다형성,Overriding)  (0) 2011.03.24
자바 객체지향의 특징2 (상속화)  (1) 2011.03.24
자바 메소드(method)  (3) 2011.03.24
자바 배열이란?  (2) 2011.03.24
자바 제어문(조건/반복/분기)  (2) 2011.03.24

0. 메소드 3요소 : Return type, Method name, Parameter

 

1. 메소드의 접근

 1) Member Method, Instance Method : 멤버변수와 같은 개념

 2) Class Method, Static Method : 클래스변수와 같은 개념

 public class MethodTest{
 public static void main(String[] args) {
  MethodTest mt = new MethodTest();
  mt.display();
  display2();
  SubTest st = new SubTest();
  st.display3();
  SubTest2.display4();
 }

 void display(){  //Member Method, Instance Method
  System.out.println("Hello, World");
 }
 static void display2(){ //Class Method, Static Method
 System.out.println("Hello, World2");
 }
}

class SubTest{
 void display3(){  //Member Method, Instance Method
  System.out.println("Hello, World3");
 }
}

class SubTest2{
 static void display4(){  //Member Method, Instance Method
  System.out.println("Hello, World4");
 }
}

 

2. Method 호출

 1) Call by value

 public class MethodTest1{
 public static void main(String[] args) {
  int result, a, b; //argument
  a=10; b=50; 
  result = hap(a,b); 
  display(a,b,result);
  a=1; b=5;
  result = hap(a,b); 
  display(a,b,result); 
 }
 static void display(int a, int b, int result){
  System.out.println(a+"부터"+b+"까지합="+result);
 }
 static int hap(int start,int last){//parameter
  int sum = 0;
  for(int i=start ; i<=last ; i++ ){
   sum += i;
  }
  return sum;
 } 
}

 1. 합계를 출력하는 메소드에

시작값과 끝값의 입력을 받아 

각각 다른 결과값을 가져올 수 있다.

 2. 출력 메소드 역시 입력값에 따라 다른 출력을 가져올 수 있다.

 

 3. Call by value는 Value type이 대상이기 때문에 값복사를 하며, 별도의 공간 2개가 따로 만들어진다. 상대방에게 영향을 주지 않는다.

 

 2) Call by Reference

 public class MethodTest2{
 int a, b;
 public static void main(String[] args) {    
  MethodTest2 mt2 = new MethodTest2();
  mt2.a = 5; mt2.b=9;
  System.out.println("mt2.a="+mt2.a+"mt2.b="+mt2.b);  
  swap(mt2);
  System.out.println("mt2.a="+mt2.a+"mt2.b="+mt2.b);
 }
 static void swap(MethodTest2 mt){
  int tmp;
  tmp = mt.a; mt.a=mt.b; mt.b=tmp; 
 }
}

  생성자의 변수로 주소값을 넘겨준다.

 public class MethodTest3{
 public static void main(String[] args) {  
  int [] array = method();
  System.out.printf("%d, %d",array[0],array[1]);
 }
 static int[] method(){
  int[] array ={5,6};
  return array;
 }
}

  배열로 받는 방법.

 

 3)Varargs (Variable Arguments)

public class MethodTest4{
 public static void main(String[] args) {
  method(1,2,3,3,"string",'A',false);  //아무거나 넣어도 된다.
 }
 static void method(Object ... array){
  for (Object obj : array ){   
   System.out.print(obj + "\t");   
  }
 }
}

 

 Variable Arguments :  

 메소드에 인자값을 다양하게 (갯수/형) 주어도 메소드에서 입력받을 수 있다.

 배열처럼 사용하지만 배열이 아니라는의미인

... 을 사용하여 모든 형을 Object로 받는다.

 

 4) Recursive Methods (재귀 함수)

  - 굳이 반복문으로 표현 할 수 있는 것을 재귀함수로 사용하지말자. (메모리 사용량 증가)

 

 5) Method Overloading(오버로딩) (메소드 중복정의) //오버라이딩이랑 다르다.

  - 메소드의 이름이 같아도 입력 parameter가 다르면 사용 할 수 있다.

 public class MethodTest6{
 public static void main(String[] args) {
  display();
  display(3);
  display(3,5);
  display(3.4);
 }
 static double display(double a){  return 1.2;}
 static void display(int a){}
 static char display(int a, int b){ return 'A';}
 static void display(){}
}

 

 6) static Methods

  - 생성자 없이 클래스명으로 접근하기위해서

  - 왜 main ()는 static인가? : 생성자 없이 바로 main()를 실행하기 위해서.

 

 

 

ps-------------------------------------

-return 은 메소드의 끝을 의미하며, 그 뒤에는 문장이 올 수 없다. 하지만 조건문 속에서는 가능하다.(조건적 return)

 static void exampleMethod( ){
intsu;
//...
System.out.println("Hello");
if (su< 10)
return;
System.out.println("World");
}

 

-String 은 Call by value의 예외이다. (값을 바꿀 수 없다)

1. 배열 : 같은 형식의 다양한값들을 담고있는 구조.

 1) 실행 될 때 생성된다.(at runtime)

 2) 생성된 후엔 구조 확장이 불가능하다.

 3) 각 형들의 초기값

  - int 형의 초기값 : 0

  - double 형의 초기값 : 0.0

  - boolean 형의 초기값 : false

  - char 형의 초기값 : '\0', '\u0000' // 프린트 할 수 없는 값이 출력되기 때문에 종료된다.

  -  Reference형의 초기값 : null

 ex) 자판기(화폐)

 import javax.swing.JOptionPane;
public class Japanki{
 public static void main(String[] args) {
  int [] array = {50000,10000,5000,1000,500,100,50,10,5,1};
  String money = JOptionPane.showInputDialog("얼마?");
  int gold = Integer.parseInt(money);
  for (int i=0; i<array.length ; i++){
   System.out.printf("%d원 =>> %d개\n", array[i], gold/array[i]);
   gold = gold%array[i];
  }
 }
}

 입력받은 값을 5만원권부터 1원짜리까지 나눌수 있는 갯수를 표시하여준다.

 

2. 다차원 배열

 1) 2차원배열 : Array of Array

   - 배열된 곳의 주소들을 배열한다는 의미로 알면 쉽다.

int [][] array = new int [3][4];   

for (int i = 0; i<array.length ; i++ ) {
   for (int j=0; j<array[0].length ;  j++){
    System.out.print("array["+i+"]["+j+"]="+array[i][j]+"\t"); 
   }
   System.out.println(""); 
  }
  System.out.println("Rectangular Array\n");

 int [][] array3 = {{2,3},{4,5,6},{7},{8,9,10,11}};
  for (int i = 0; i < array3.length ;i++ ){
   for (int j = 0; j < array3[i].length ;j++ ){
    System.out.print("array["+i+"]["+j+"]="+array3[i][j]+"\t"); 
   }
   System.out.println(""); 
  }
   System.out.println("Ragged Array\n");

 Rectangular Array : 행 열 고정

 Ragged Array : 행 고정 열 변환

 

3. Copying Arrays : 값복사와 주소복사

 int [] original = {1,2,3,4,5};
 int [] target = {9,8,7,6,5,4,3,2,1};

 target = original;

  nt [] src = {1,2,3,4,5};
  int [] dest = {9,8,7};
  System.arraycopy(src,0,dest,0,3);

 주소복사

 값복사 : 두 배열의 길이를 알고있어야한다.

 

'Programming > JAVA' 카테고리의 다른 글

자바 객체지향의 특징 1(캡슐화,생성자,this)  (4) 2011.03.24
자바 메소드(method)  (3) 2011.03.24
자바 제어문(조건/반복/분기)  (2) 2011.03.24
JAVA 문법과 연산자  (2) 2011.03.24
JAVA 언어의 법칙  (1) 2011.03.24

+ Recent posts