티스토리 뷰

LANGUAGE/JAVA

[JAVA] jdk7의 신기능

찰떡쿠키부스트 2017. 11. 15. 10:55

 

# static import문
[ex]
import static java.lang.System.out;
class A{
 public static void main(String args[]){
 System.out.println(100);
 out.println(200);
 }
}


# Closeable인터페이스
jdk7에서 finally를 사용하지 않아도
자동으로 자원을 회수하는 기능이 추가됨.
Closeable인터페이스를 구현한 모든 객체에
대해서 자동으로 자원회수기능이 있다.

[ex]

기존- try{}    catch(){}    finally{}

추가기능 -try(객체생성){}     catch(){}

[ex]
import java.io.*;
class A{
 public static void main(String args[]){
 try(A o=new A()){
          o.test();
 }catch(Exception e){
 System.out.println("예외처리");
 }
 }
}
class B implements Closeable{
 public void close(){
 System.out.println("자원정리");
 }
void test() throws Exception{
 throw new Exception("폭탄");
 }
}

# jdk7에서는 숫자에 _(밑줄)을 추가할 수 있는 기능이 추가됨.
[ex]
class A{
 public static void main(String args[]){
 int a=1000;
 int b=1_000;
 int c=1_000_000;
 System.out.println(a+b);
 System.out.println(c);
 }
}


# jdk7에서는 숫자앞에 0b를 선언하면 2진수로 선언됨.

[ex]
class A{
 public static void main(String args[]){
 int a=0b1000;
 int b=0b100;
 System.out.println(a); // 8
 System.out.println(b); // 4
 }
}


# jdk7에서 Exception처리가 향상되었다.
다중catch절을 하나로 줄일 수 있는 기능 추가됨.
[ex]
class A{
 public static void main(String args[]){
 Integer.parseInt("a");
 int a=10/0;

 try{
 Integer.parseInt("a");
 int a=10/0;
 }catch(NumberFormatException | ArithmeticException e){
 System.out.println("예외처리");
 }
 }
}


# <? extends 상위타입>

[ex] test메서드를 호출할때 Animal의
 자손타입만 인자값으로 허용하려면?

import java.util.*;
class A{
 static void test(ArrayList<? extends Animal> list){
 }
 public static void main(String args[]){
 test(new ArrayList<Dog>());
 test(new ArrayList<Cat>());
 test(new ArrayList<Animal>());
 // test(new ArrayList<A>()); 컴파일에러
}
}
class Animal{}
class Dog extends Animal{}
class Cat extends Animal{}


[an] ArrayList<? extends Animal> list=new ArrayList<Dog>();


[ex] test메서드를 호출할때 HomelessDog의
 부모타입만 인자값으로 허용하려면?

 <? super 하위타입>

import java.util.*;
class A{
 public static void main(String args[]){
 test(new ArrayList<Dog>());
 test(new ArrayList<Animal>());
 //test(new ArrayList<Cat>()); 컴파일에러
test(new ArrayList<HomelessDog>());
 //test(new ArrayList<StarDog>()); 컴파일에러
}
}
class Animal{}
class Dog extends Animal{}
class HomelessDog extends Dog{}
class StarDog extends Dog{}
class Cat extends Animal{}

[an] static void test(ArrayList<? super HomelessDog> list){

 }


# 제너릭클래스&제너릭메서드

[ex] test제너릭메서드를 선언하시오.

import java.util.*;
class A{
 public static void main(String args[]){
 test(new ArrayList<String>());
 test(new ArrayList<Integer>());
 test(new ArrayList<A>());
 }
}
[an] static <T> void test(ArrayList<T> list){
 }

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

[JAVA] synchronized,Thread,제너릭  (0) 2017.11.15
[JAVA] enum,Graphics  (0) 2017.11.15
[JAVA] io,network  (0) 2017.11.15
[JAVA] awt.menu ,io  (0) 2017.11.15
[JAVA] Calendar 객체  (0) 2017.11.15
댓글