JAVA 개인 공부 - 유튜브 programmers * 열거형 모르겠다.

concat

 String str = new String ("hello") ; 

간단하게 이렇게 쓸 수 있다. : String str = "hello"; 

System.out.println(str.concat(" world" ) ; 


str = str.concat("world"); 


str.substring
str.substring (3) 시작 인덱스부터 마지막까지    
str.substring(3, 6 ); 3번부터 6번까지만 잘라내기 

String 클래스 

모든 클래스는 new 연산자를 이용해야지만 인스턴스를 만들어 낼 수 있는데 
new 연산자를 이용하지 않고 인스턴스를 만들 수 있따. 
String str1 = "hello" ; 
String str2 = new String("hello"); 
두가지 방법 모두 된다. 


String str1 = "hello"; 
String str2 = "hello";
hello 가 생성되면 이 hello는 상수들이 저장되는 영역에 저장한다. (상수영역)

str1 과 str2 가 hello가 상수영역에 있는지 확인하고 동일한게 있으면 새로 만들지 않음
str1 과 str2는 같은 인스턴스를 가리키고 있다. 


String str3 = new String("hello"); 
String str3 = new String("hello"); 

new 가 나오면 무조건 상수영역에 있는 hello 를 만들지 않는다. 
hello 가 새로운 heap영역에 만들어진다. 

*참조형일때는 실제 메모리영역에 가리키는 주소가 같은지를 본다. 

str1 과 str2 만 같은주소. 


배열 ( array) 참조형타입이다. 

1. 1차원 배열 


int [] array1 = new int[100] ; 

int[] array2 = new int[]{1,2,3,4}; 
int [] array3 = {1,2,3,4}; 




변수의 scope 

변수의 scope 는 그 변수가 선언된 블럭이다. 
즉 for 문 안에서 선언이 된다면 그 변수는 for 문 안에서만 사용된다. 

for ( ; ; ) { 
여기에 sum 변수를 선언하면 for 문이 실행되고 다시 실행될때마다 sum 변수는 선언이 되니까 계속 더하고 더하는 값을 얻을 수 없다. 
}


2차원 배열 

int[][] array4 = new int[3][4]; 
array4[0][1] = 10 ; 

int[][] array5 = new int[3][];
이렇게 만들 수 있다. 
array5[0] = new int[1]; 
array5[0][0] = 10 ; 


int[][] array6 = { {1} , {1,2}, {1,2,3}}; 

System.out.println(array6[0][0]); 

System.out.println(array6[2][2]); 
 


for each 

int[] iarr = {10, 20,30,40,50} ; 

for(int i = 0 ; i <iarr.length ; i++) { 
int value = iarr[i] ; 
Systme.out.println(value); 
}

--> for each for(각 배열의 값을 저장해줄 변수 : 배열 ) { } 

for(int value:iarr){ 
System.out.println(value); 


new 
객체를 생성하기 위해서 사용한다. 


method 
란 Class 가 가지고 있는 기능
메서드는 Class 내부에 선언 된다. 



static



public class VariableScopeExam { 

int globalScope = 10; 
-> 이렇게 선언된 globalScope 는 포함하는 블럭이 전체이다. 
이 변수는 이 클래스 전체가 사용범위라고 할 수 있다. 
static int staticVal = 7; 


public void scopeTest ( int value) { 
       int localScope = 20; 

      System.out.println(globalScope) ; 
     -> 사용 가능
      System.out.println(localScope);
     -> 사용가능
      System.out.println(value);
    -> 사용가능 메서드 선언부에 존재하므로 사용범위는 해당 메서드 블럭 내
}

다른 메서드 내에서 사용할 수 있는지 

public void scopeTest2(int value2) { 

     System.out.println(globalScope) ; 
     -> 사용 가능
      System.out.println(localScope);
     -> 사용불가
      System.out.println(value);
      -> 사용 불가 
      System.out.println(value2);
     -> 사용 가능 
사용 불가이유 : 범위. 이 변수를 선언한 블럭에 포함되어 있지 않아서

public static void main (String[] args) { 
     System.out.println(globalScope) ; 
     -> 사용 불가   : 이유 : static 때문 
      System.out.println(localScope);
     -> 사용 불가
      System.out.println(value);
      -> 사용 불가 
     System.out.println(staticVal); 
     -> 사용 가능  : 
모든 클래스는 인스턴스화 (객체 생성) 하지 않은 채로 사용할 수 없다. 
메인 메서드에는 static 키워드가 붙어 있는데 
지금까지 클래스를 정의하고 해당 클래스를 new 하지 않았음에도 메인 메서드가 실행된 이유 
키워드 static 을 사용하면 인스턴스화 하지 않아도 사용할 수 있다. 
static 한 메서드 내에서 static 하지 않은 메서드는 사용할 수 없다. 
static 한 메서드가 사용되는 시점에 해당 클래스가 인스턴스화 되지 않았을수도 있기 때문이다. 

static 한 변수들은 static 하지 않은 메서드 내에서는 사용해도 문제가 되지 않는다. 
static 한 메인메서드에서 static 하지 않은 변수들을 사용하려면 객체를 생성하면 된다 
: VariableScopeExam v1 = new VariableScopeExam; 
System.out.println(v1.globalScope);
VariableScopeExam v2 = new VariableScopeExam; 
System.out.println(v2.globalScope);
객체안에 변수를 저장할 수 있는 자리를 별도로 지정한다. 
v1.globalScope = 10;
v2.globalScope = 20; 
System.out.println(v1.globalScope);  -> 10으로 출력
System.out.println(v2.globalScope);  -> 20 으로 출력 

static 한 변수에도 값을 부여해볼까. 
v1.staticVal = 50 ; 
v2.staticVal = 100; 
System.out.println(v1.staticVal); -> 100출력
System.out.println(v2.staticVal); -> 100 출력 
?? why 
static한  field 는 인스턴스 생성시에 만들어지는 것이 아니고 값을 저장할 수 있는 공간이 1개밖에 없다. 
즉 값을 공유한다. -> 이런변수를 클래스 변수라고 한다. 
globalScope 같은 경우는 인스턴스가 생성될때 생성되기 때문에 인스턴스 변수라고 한다. 

클래스 변수는 인스턴스가 생성하지 않아도 사용할 수 있기 때문에
v2.~ 대신 클래스이름을 직접. 사용가능
System.out.println(VariableScopeExam.staticVal) ; 로 직접 사용가능하다. 이렇게 사용하는 것이 조금 더 바람직하다고 할 수 있다. 


}


열거형 


열거타입 

jdk 5에서 추가된 문법 



생성자 

new 연산자 다음에 반드시 생성자가 나와야 한다. 
Car c1 = new Car(); 생성자부분

특징 1) 메소드와는 다르게 return 타입을 가지고 있지 않는다. 
특징 2 ) 생성자를 프로그래머가 만들지 않으면 매개변수가 없는 생성자가 컴파일할때 자동으로 만들어짐
특징 3) 프로그래머가 생성자를 하나라도 만들었다면 기본 생성자(매게변수가 없는 생성자)  는 자동으로 만들어지지 않는다. 


생성자 : 객체가 될때 필드를 초기화하는 역할 

생성자를 Car 클래스에 추가해주면
public Car(String n) { 
name = n; 
}
CarExam2 라는 메인 클래스에 
(Car 클래스에 기본생성자가 없으니까 ) Car 객체를 만들 때 더이상 기본생성자로 만들 수가 없다 ( 기본생성자 : Car c1 = new Car(); ) 
Car c2 = new Car("소방차") ; 
이렇게 Car 클래스에 만들어진 생성자를 쓸 수 있다. 
Car c3 = new Car("구급차") ; 

프린트하려면 : System.out.println(c2.name); 



this 


package javaStudy ; 

public class Car{
String name
int number ; 

  (생성자)  public Car(String name){ 
              this.name name  ; 

}

}

--------------------------------------------------------------------------------

package javaStudy; 

public class CarExam2 { 
    public static void main(String[] args) { 
        Car c2 = new Car("소방차") ; 
        Car c3 = new Car("구급차") ; 
        
        System.out.println(c2.name); -> 소방차가 출력된다. 


** 참고 : 클래스안에서 자기자신이 가지고 있는 메서드를 사용하고 싶을때도 this.메서드명 이렇게 호출가능 
나의 생성자를 호출할때에도 this 라는 키워드를 사용해서 호출 할 수 있다. 


메소드 오버로딩 

매개변수의 수, 타입이 다른경우 동일한 이름으로 메소드를 여러개 정의할 수 있다. 
3개의 메소드를 만들어볼거다. 

package javaStudy ; 

public class MyClass2{ 

public int plus ( int x , int y ){ 
    return x + y ; 
}

public int plus ( int x , int y , int z ) {
    return x + y + z ; 
}

public String plus ( String x , String y ) { 
    return x + y ; 
}


:똑같은 이름으로 메서드 3개를 정의했지 : 메서드 오버로딩 -> 매개변수의 수와 타입이 중요

public int plus ( int i , int j ) { 
--> 사용불가. 매개변수의 이름이 아니라 타입이 중요. 

}

-----------------------------------------------이용해보자

package javaStudy ; 
public class MethodOverloadExam { 
public static void main (String[] args) { 
    Myclass2 m = new Myclass2(); (생성자) 

System.out.println(m.plus(4, 5) ) ; -> 9 가 리턴된다. 


System.out.println(m.plus(4, 6, 7) ) ; -> 17이 리턴된다. 

System.out.println(m.plus("hello", "world") ) ; -> helloworld 가 나온다.

      }

}


패키지 

다른 패키지에 들어있는 클래스를 사용하기 위해서는 java 에 lang package 를 제외하고   import 를 해주어야 한다. 
ctrl+shift+o 

관련있는 클래스들 끼리 모아서 패키지 형태로 관리한다. 



상속
 class 자식클래스 extends 부모클래스이름 

부모가가지고 있는 것을 자식클래스에서도 사용가능 



접근제한자

1.public 


어떤 클래스든 접근할수 있다. 

public int p = 3 ; 


2.protected

protected int p2 = 4; 

같은 패키지인 경우 접근 허용
다른 패키지라도 상속을 받은 경우 접근을 허용한다.

3. private int i = 1; 
자기자신만 접근이 가능하다.


4.int k = 2 ; 

default 접근지정자 아무것도 쓰지 않은 경우 자기자신과 같은 패키지 안에 접근 가능


public > protected default > private 



AccessObject obj = new AccessObject 
















댓글