1. Exception

 1) Riun time 때 발생 할 수 있는 사용자의 에러를 처리 해 주기위해 사용한다.

 2) exception의 구조


   - RuntimeException(Unchecked Exception)의 경우 try~catch가 없어도(사용자가 조심하면된다.) 상관없지만 일반 Exception의 경우는 반드시 try~catch이 필요(컴파일 에러)하다(Checked Exception)

 

  3) Exception의 처리 문구 확인

   - String getmessage() : 개발자가 작성한 오류문구를 출력한다. 사용자에게 보여줄 용도

   - void printStackTrace() : 에러 죵류와 에러가 발생한 곳을 표시한다. 개발자용

   - String toString () : 에러의 종류를 출력. 개발자용

 

  4) Try ~ catch

   - try에서 예외를 검사하고 발생 시 catch 구문이 실행된다. 예외가 발생하지 않으면 catch문은 처리되지 않는다.

   - 발생한 예외는 호출한 곳에서 처리가 가능하다..

   - 예외는 자신의 예외만을 catch 할 수 있다. 여러개의 오류가 예상되면 여러개의 catch를 쓰면된다.

   - 예상할수 없는 예외를 잡는 방법은 catch(Exception ex)를 사용한다. 모든 예외의 부모형으로 형변환이 가능하기 때문에 사용하는것으로 catch문 들의 가장 마지막에 사용한다.(절자적으로 감사하기때문에..

 public class ExceptionDemo2 {
 public static void main(String[] args) {
  a();
 }
 static void a(){
  b();
 }
 static void b(){
  try{
   c();
  }catch(ArrayIndexOutOfBoundsException e){ 
   System.out.println("여기서 ArrayIndexOutOfBoundsException"); 
  }catch(NullPointerException ex){
   System.out.println("여기서 NullPointerException");
  }catch(NegativeArraySizeException ex){
   System.out.println("여기서 NegativeArraySizeException");
  }catch(Exception ex){   // 가장 아래에 써야한다.
   System.out.println("내가 진짜다");
  }
 }
 static void c(){
  d();
 }
 static void d(){
  System.out.println(5 / 0);
 }
}

 

 5) RuntimeException

  -

 6) Declaring Exceptions (throws)

  - method()안에 throw된 exception이 있다는 걸 표시하는 것으로 내부에 throw된 exception이 checked 인지 uncheched인지 확인하여 try~catch를 사용해야한다.

 public class ExceptionDemo3 {
 public static void main(String[] args) {
  Student chulsu = null;
  try{
  chulsu = new Student(110);
  System.out.println(chulsu);
  }catch(RuntimeException e){
   javax.swing.JOptionPane.showMessageDialog(null, e.getMessage());
  }
 }
}
class Student{
 private int kor;
 public Student(int kor) {
  if(kor >= 0 && kor <= 100) this.kor = kor; 
  else throw new RuntimeException("점수 제대로 입력해라.");
  
 }
 @Override
 public String toString(){
  return String.format("kor = %d\n", this.kor); 
 }
}

 public class ExceptionDemo3 {
 public static void main(String[] args) {
  Student chulsu = null;
  try{
  chulsu = new Student(110);
  System.out.println(chulsu);
  }catch(Exception e){
   javax.swing.JOptionPane.showMessageDialog(null, e.getMessage());
  }
 }
}
class Student{
 private int kor;
 public Student(int kor) throws Exception{//t선언
  if(kor >= 0 && kor <= 100) this.kor = kor; 
  else throw new Exception("점수 제대로 입력해라.");
  
 }
 @Override
 public String toString(){
  return String.format("kor = %d\n", this.kor); 
 }
}
Unchecked Exception (Runtime error) Checked Exception (Compile error) 

 

 6) Finally

  - try~catch 이후에 해야할 것들을 정의 한다.

  - ex) conn.close() //디비 접속 해제

 

 7) Exception 생성

  - cheched 인가 uncheched인가

  - 생성자 Overrind을 할건지 안할지

 public class KoreanException extends RuntimeException { // unchecked exception 생성
 public KoreanException(String msg){
  super(msg);
 }
}

 

 

2. Assertions

  1) JAVA에서 지원하는 기본적인 디버깅 방법이다.

 public class AssertionDemo{  //run as 의 argument에 vm입력값에 옵션 -ea를 설정한 후 출력확인,
 public static void main(String[] args) {
  int sum = 0, i;
  for(i = 1 ; i <= 10 ; i++){
   sum += 1;
  }
  assert i == 11 :  "i = " + i;
  assert sum > 50 : "sum 값에 이상이 있습니다";
  System.out.println("sum = " + sum);
 }
}

1. Static Methods의 목적

 1) 생성자 없이 사용 할 수 있다.

 public class StaticDemo {
 public static void main(String[] args){
  Demo[] d = new Demo[5];
  for (int i = 0; i < d.length; i++) {
   d[i] = new Demo();
  }
  System.out.println(d[0].su);
  System.out.println(d[0].num);
 }
}
class Demo{
 int su;
 static int num;
 public Demo(){
  su++;
  num++;
 }
}

 Static 변수인 num만 증가하고 su는 따로 객체를 만들기 때문에 5개의 1이 생긴다.

 

2. Static Initializers (스태틱변수 초기화)

 1) 스테틱 메모리 접근.

 public class StaticDemo1 {
 private static int su = method(); //static 멤버가 가장 먼저 메모리에 올리오기 때문에 main() 보다 method()가 먼저올라온다.
 public static void main(String[] args){
  System.out.println(su);  
 }
 private static int method(){
  System.out.println("i'm method");
  return 1000;
 }
}

 

 2) 맴버변수는 생성자가 초기화 / 스태틱변수는 스태틱 블록이 초기화 한다.

public class StaticDemo2 {
 private int su;
 private static int num;
 public StaticDemo2(){
  System.out.println("나는 생성자");
  su=10;
 } 
 public static void main(String[] args) { 
  System.out.println("나는 메인");
 }
 static{
  System.out.println("나는 스태틱 초기화 블록");
  num = 100;
 }
}

 가장 먼저 스태틱 초기화블록이 실행되고 메인이 실행된다. 스태틱 초기화블록은 최초 한번 실행되고

 

 

3. Final

 1) Final 상수 역시 생성자에서 초기화 할 수 있다.

 2) Final Methods

 

4. Deprecation

 1) java가 버전업 되면서 수정되거나 업데이트 된 클래스나 메소드를 호출 할 때 표시된다.

 2) ex : Date => Calander

 

5. Inner Classes

  1) Nested Class (Static class, 중첩클래스)

   - why : static class 를 사용해 패키징화 하기 위해 사용한다. (new 로 생성 할 필요없이 접근 가능)

   - 생성방법 : Outer.Inner in = new Outer.Inner();

   - 제한사항 : Outer의 member변수, member 메소드는 사용할 수 없다. (생성한 후 사용 가능)

 
public class NestedClassDemo {
 public static void main(String[] args) {
  Outer.Inner in = new Outer.Inner(); // Outer를 생성하지 않아도 static인 Inner에 접근가능.
  in.method1();
 }
}
class Outer{
 private int a;
 public int b;
 public Outer(){   //outer class constructor
  this.a = 5;   this.b = 10;
 }
 public static void method(){  //outer class method
  System.out.println("나는 스태틱");
 }
 static class Inner{
  private int c;
  public int d;
  public Inner(){
   this.c = 5;
   this.d = 10;
  }
  public void method1(){
   Outer out = new Outer();
   System.out.println("a ="+out.a); //static은 멤버에 접근 불가능. 주소를 가져야 하기때문에 생성자 필요
   method();  //static은 static에 바로 접근이 가능하다.
  }
  public static void method2(){}
 }
}

 

 2) Member Class

   - why : 다중 상속을 하기위해 사용한다.

   - 생성방법 : Outer.Inner in = 바깥주소.new Inner();

   - 제한사항 : Inner는 static 변수, static 메소드를 가질 수 없다.

 public class MemberClassDemo {
 public static void main(String[] args) {
  Outer1 out = new Outer1();
  Outer1.Inner1 in = out.new Inner1();
 }
}
 class Outer1{
 private int a = 5;
 private static int b= 10;
  class Inner1{
   private int c = 100;
 //  public static int d =4; //static 변수 사용 할 수 없다.
   public void method(){
    System.out.println("a="+a);
    System.out.println("b="+b);
   }  
 }
}

 

 3) Local Class

   - why :

   - 생성방법 :

   - 제한사항 : 메소드 속에서는 절차적이기 때문에 순서가있다. / public, private,protected 접근자 사용불가 / static 사용 불가 / 로컬클래스가 속해있는 메소드의 지역변수를 사용할 수 없다( 지역 상수는 사용 가능하다)

 public class LocalClassDemo {
 public static void main(String[] args) {
  Outer2 out = new Outer2();
  out.method();
 }
}
class Outer2{
 private int a= 5;
 private static int b = 10;
 public void method(){
  int c = 100; //메소드의 지역변수
  final int c2 = 100;  //지역 상수
  class Inner2{
   private int d = 100;
   public Inner2(){
    System.out.println("나는 생성자");
   }
   public void display(){ 
    System.out.println(a+b+d);
   // System.out.println(c);  // 사용 불가
    System.out.println(c2); //사용가능
   }
  }
  Inner2 in = new Inner2(); // method() 내에서는 순차적으로 처리된다.(Inner2를 알고있어야 생성가능)
  in.display();
 }
}

 

4) Anonymous Class

   - why : 상속 관계가 아니어도 Overriding 할 수 있다.

   - 생성방법 :

   - 제한사항 :

 public class AnonymousClassDemo {
 public static void main(String[] args) {
  Super s = new Super(){
   public void display(){
    System.out.println("hello22");
   }
  };
  s.display();
 }
}
class Super{
 public void display(){
  System.out.println("hello");
 }
}

 

 

6. Enum

 1) 고정된 갯수의 나열을 갖는 데이터를 갖는다.

 2) 데이터 형이 없다.

 3) 선언될 상수가 가장 윗줄에 작성되어야 한다.

 4) 생성자는 public을 사용 할 수 없다.

 public class EnumDemo {
 public static void main(String[] args) {
  for (Subjects s : Subjects.values()) {
   System.out.print(s+"-->");
   System.out.print(s.ordinal()+"==>"); //나열순서 출력
   System.out.print(s.get()+"==>");
   System.out.println(getInfo(s));
  }
 }
 static String getInfo(Subjects s){
  String info = null;
  switch(s){
  case JAVA : info ="열정" ; break;
  case JDBC : info ="Oracle" ; break;
  case JSP : info ="Javascript" ; break;
  case Android : info ="SmartPhone" ; break;
  case Project : info ="Idea" ; break;
  }
  return info;
 }
}

 public enum Subjects {
 JAVA(1), JDBC(10), JSP(100), Android(1000), Project(10000);
 Subjects(int v){ //생성자는 public 사용 안됨.
  this.v = v;
 }
 private final int v;
 public int get(){
  return this.v;
 }
}

 

추상화

 

1. Abstract Methods 추상 메소드  (Override의 강제성을 주기위해 사용한다)

 1) 바디를 정의하지않는 메소드로 상속해 줄 수 있으며 이를 상속 받은 클래스는 반드시 재 정의 해야한다.(Overriding)

 public class AbstractDemo {
 public static void main(String[] args) {
  Jasic j = new Jasic();
  j.display();
 }
}

abstract class Bumo{  // abstract 메소드를 가지고있는 클래스 역시 absract로 선언.
 abstract void display(); // 바디를 정의하지않는 메소드는 앞에 abstract를 선언해야한다.
}
class Jasic extends Bumo{
 void display(){
  System.out.println("son");
 }
}

 

2. Abstract Class 추상 클래스

 1) new로 생성할 수 없다. (인스턴스화 할 수 없다, 메모리에 올릴 수 없다)

 2) abstract 메소드가 없는 정상적인 Class  역시 Abstract로 선언 할 수 있다.

 

3. Interface : implements로 상속(구현한다)받는다.

 1) public abstract static 을 생략한 클래스라고 생각하면된다.

 2) interface속의 변수는 public static final이 생략되어있다. 따라서 모두 초기화를 해야한다.

 3) interface의 메소드는 public abstract가 생략되어있다.

 4) interface의 하위클래스는 반드시 메소드 재정의 해야한다.

 5) extends를 먼저 선언한후 implements를 쓴다. 

 6) 하위 클래스에서 인터페이스의 메소드를 재정의할 때 반드시 public을 써야한다.

 7) Interface Type의 레퍼런스변수는 해당 인터페이스 리소스만 접근가능.

 8) Interface Type의 배열을 생성할 수 있는데, 이는 interface자식들의 주소를 받을 수 있는 수첩이다.

 9) Interface속에있는 변수는 클래스변수이기 때문에 interface이름으로 접근한다.

 

4. flag interface : 멤버가 하나도 없는 인터페이스

 1) ex : clone() 사용.

   - Cloneable : 모든 클래스가 값을 복사 할 수 있는 권한이 없다. 그래서 권환을 확인하는 인터페이스.

 public class CloneDemo {
 public static void main(String[] args) {
  Demo original = new Demo(5);
 // Demo copy = original; //주소복사
 // Demo copy = (Demo)original.clone(); //사용할 수 없음.
  Demo copy = original.copy();
 }
}
class Demo implements Cloneable{ // 멤버가 없는 인터페이스 이지만 상속 받을 경우 copy권한을 얻게된다.
 private int su;
 public Demo(int su){
  this.su = su;
 }
 public void set(int su){
  this.su = su;
 }
 public int get(){
  return this.su;
 }
 public Demo copy(){
  Object obj = null;
  try {
   obj=clone();
  } catch (CloneNotSupportedException e) {
   System.out.println("복제 실패함");
  }
  return (Demo)obj;
 } 
}

 

 

5. Package

 1) class를 묶는 단위. (보통 도메인을 사용하여 com.javasoft.lib.Demo 형식으로 작성한다)

 2) cmd 에서 컴파일 할 때 -d 옵션으로 경로를 설정해야한다.

 javac–d D:\project\first Employee.java

 3) 클래스 패스 설정 : 변경되지 않는 경로를 가지고있다면 환경변수에서 지정하면된다.

 4) jar 파일 만들기. (유닉스의 tar과 같다.)

   - 압축 상태의 클래스파일들을 사용할 수 있다.

   - jar파일의 경로를  import하여 사용 할 수 있다.

 5) eclipse 에서 외부 jar 가져오기.

   - 프로젝트 선택 마우스오른쪽 -> build path -> add Archive..

 6) 도스와 eclipse 환경에서의 Package 접근이 약간 다르다. (

 public class Resume {
 private int a =5;
 int b = 10; // default는 하위 클래스도 접근 불가능
 protected int c = 100;  //상속되며 하위 클래스를 통해 접근이 가능
 public int d =5000; //다른 패키지에서도 접근 가능.
}

 

 

6. Import static

import static java.lang.System.*;
import static java.lang.Math.*;  //or import static java.lang.Math.random    메소드뒤에 ()까지 쓰면 안된다.

public class StaticImportDemo {
 public static void main(String[] args) {
  out.println("hello,world");  //System 클래스를 import했기때문에 쓰지않아도 된다.
  int r = (int)(random()*10+1);
 }
}

 

 

  

 

 

 

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

1. absract 와 final은 상극

2. this()와 super()는 상극

3. shallow copy : 주소복사 / deep copy : 값복사

1. 객체지향의 주요 특성.
 1) 추상화 (Abstraction)
 2) 캡슐화 (Encapsulation)
 3) 상속화 (Inheritance)
 
 4) 다형성 (Polymorphism)
     1. Primitive Type
      1) implicit conversion
      2) explicit conversion
     2. Reference Type
      1) 서로 다른 객체는 강제적, 암시적 형변환 안된다.

 public class CastDemo {
 public static void main(String[] args) {
  Test td = new Test();
  Demo d = new Demo();
  td = (Test)d;  // 오류
 }
}

class Test{
 int su = 5;
}
class Demo{
 String name = "taehyung";
}


      2) 자식 --> 부모로 형변환 : 강제적, 암시적 모두 성공한다.
      3) 부모 --> 자식으로 형변환 : 강제적 형변환만 가능하고, 런타임 때 오류발생가능 (반드시 instanceof()로 검증해야한다.)

 public class CastDemo {
 public static void main(String[] args) {
  Test t = new Test();
  Demo d = new Demo();
  t = d;   //자동 형변환
  t = (Test)d;  // 강제 형변환
 }
}
class Test{
 int su = 5;
}
class Demo extends Test{  // 상속
 String name = "taehyung";
}

 public class CastDemo {
 public static void main(String[] args) {
  Test t = new Test();
  Demo d = new Demo();
  d = t;  // 자동 형변환 오류
  d = (Demo)t;  //강제 형변환은 된다
 }
}
class Test{
 int su = 5;
}
class Demo extends Test{
 String name = "taehyung";
}
 public class CastDemo {
 public static void main(String[] args) {
  Test t = new Test();
  Demo d = new Demo();
  if (t instanceof Demo) d = (Demo)t;
  else System.out.println("cannot");
 }
}
class Test{
 int su = 5;
}
class Demo extends Test{
 String name = "taehyung";
}
 자식 --> 부모  부모 -->자식  부모 --> 자식(instanceof())
 
 
 
 
ex) 포유류 형을 상속받은 개나 고양이 들의 형태를 다시 포유류로 형변환이 된다.

 void display(int choice){
  Mammal m = null;   // 경우에 따라 자식의 형태가 부모형으로 변환되어 들어간다.
  switch (choice) {
  case 1: m = new Dog();   break;
  case 2: m = new Cat();  break;
  case 3: m = new Korean();  break;
  case 4: m = new American();  break;
  default:System.out.println("누구냐 넌,"); break;
  }
  m.saySomething();  // 각 종족에 따른 울음소리를 실행하는 메소드

 

ex2) 카센터 자동차 수리

 public class CarCentar {
 public static void main(String[] args) {
  CarCentar cc = new CarCentar();
  Matiz m = new Matiz("마티즈");
  Carnival c = new Carnival("카니발");
  Sonata s = new Sonata("소나타");
  cc.repair(m);
 }
 void repair(Car c){   //부모형 변수에 자식들의 입력을 자동으로 받는다.
  if (c instanceof Sonata) { // 형태를 검사한다.
   System.out.println("현대차 ");
  }else if(c instanceof Matiz){
   System.out.println("대우차 ");
  }else if(c instanceof Carnival){
   System.out.println("기아차 ");
  }  
  System.out.println(c.getName()+" 수리완료!"); //들어온 형태에 상관없이 getName메소드를 사용할수있다.
 }
}

 

 

 

 

 

 

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

1. 1) tightly coupled(Early Binding) : 컴파일 때.

   2) loosely coupled(Late binding) : 런타임 때

 

 

2. Overriding 할 때 자식은 부모보다 권한이 작으면 안된다.

 private < default < protected < public

 

+ Recent posts