Collection FrameWork는 값을 담을수있는 그릇을 의미한다
list는 순서를 유지하고 중복을허용한다
set은 순서를 유지하지 않고 중복을 허용하지 않는다

 

//public class
//main
String [] arr = new String[2];
arr[0] = "apple";
arr[1] = "orange";
arr[2] = "grape"; //배열의 크기가 2 이므로 error가 생긴다

for(int i=0;i<arr.length;i++) {
System.out.println(arr[i]);
} //일반적인 배열을 이용하는방법
--------

import java.util.ArrayList;

//public class
//main 
ArrayList al = new ArrayList();
al.add("apple");
al.add("orange");
al.add("grape"); 

//add란 method를 이용해 data를 입력한다

//data를 추가한만큰 배열크기가 증가한다 

//ArrayList는 Object type으로 값을 저장하기때문에

//모든 data type을 입력할수있다


for(int i=0;i<al.size();i++) {
String str = (String)al.get(i); 

System.out.println(str);

//ArrayList 는 size를 이용해 크기를 확인하고

//get이란 method를 이용해 값을 불러온다

//자식type으로 부모type의 data를 가져올때 형변환을해줘야한다

-------

import java.util.ArrayList;

//public class
//main 
ArrayList<String> al = new ArrayList<String>(); 

//generic을 이용해 String type 의 ArrayList를 만든다
al.add("apple"); 
al.add("orange"); 
al.add("grape"); 


for(int i=0;i<al.size();i++) { 
String str = al.get(i); 

System.out.println(str);

//generic을 이용할경우 형변환을 안해줘도된다

-----------

import java.util.ArrayList;

import java.util.Iterator;

import java.util.HashSet;

//public class

//main
ArrayList<String> al = new ArrayList<String>();
//ArrayList를 Collection으로 바꿔도 부모형이기때문에 문제가없다
al.add("first");
al.add("second");
al.sdd("third");
al.add("third");//중복이 가능하다

Iterator ai = al.iterator(); //Iterator은 collection에 접근하기위한 객체이다
while(ai.hasNext()) { 
System.out.println(ai.next()); 
} //순서를 유지하면서 중복된 data도 출력한다

HashSet hs = new HashSet();
//HashSet을 Collection으로 바꿔도 부모형이기때문에 문제가없다
hs.add("first");
hs.add("second");
hs.add("third");
hs.add("third"); //중복이 불가능하다

Iterator hi = hs.iterator();
while(hi.hasNext()) {
System.out.prinln(hi.next());
//순서가 유지되지않고 중복된 data를 허용하지 않는다

 

//Iterator은 hasNext, next, remove라는 3개의 method를 가지고있다 
//hasNext: 접근가능요소를 점검하고 true,false값을 반환한다 
//next: true값으로 읽어올 요소가 있다면 가져온다 
//remove는 next다음 요소를 지우는데 사용된다 
-----------

import java.util.HashSet;

//public class

//main
HashSet<String> A = new HashSet<String>();
A.add("a");
A.add("b");
A.add("c");

HashSet B = new HashSet();
B.add("c");
B.add("d");
B.add("e");

HashSet C = new HashSet();
C.add("a");
C.add("b");

A.containsAll(B); //containsAll method는 부분집합인경우  true값을 반환한다
System.out.println(A.containsAll(B)); //false값이 나온다
System.out.println(A.containsAll(C)); //true값이 나온다

A.addAll(B); //A에 중복된값을 제외한 B값을 더해준다(합집합), 출력시 abcde값 모두가 출력된다
A.retainAll(B): //중복된값을 출력(교칩합), 출력시 c값이 출력된다
A.removeAll(B): //A에 중복된 B값을 제외한다(차집합), 출력시 ab출력
Iterator hi = A.iterator();
while(hi.hasNext()) {
System.out.println(hi.next());
} //hasNext로 각요소에 접근해서 next로 가져온다
--------

import java.util.HashMap;

import java.util.Set;

import java.util.Set;

//public class
//main
//Map은 key와 value의 값으로 구성되있는데

//key값은 중복되어선안되지만 value값은 중복을 허용한다


HashMap<String, String> tel = new HashMap<String, Integer>();

//put method를 이용하여 data를 입력한다
tel.put("seoul", "01");  
tel.put("busan", "02");
tel.put("daegu", "03");

 

//data를 불러오기위해 get(key) 을 이용한다
System.out.println(tel.get("seoul"));  
System.out.println(tel.get("busan"));
System.out.println(tel.get("daegu"));

 

//Map class에 각각의 key,value값을 entry 라고하고 이를 Entry class라고한다 

//Map 이란 interface안에 entrySet method를 이용해서

//entry객체로 set을 구성하여 iterator로 접근할수있다

//Entry class에는 Map에 접근하기위해 getKey,getValue method가 존재한다
Set set = tel.entrySet(); //set을 만들면 iterator를 이용할수있다
Iterator it = set.iterator(); 
while(it.hasNext()) {
Map.Entry e = (Map.Entry)it.next(); //entry가 Object type이기때문에 형변환을 해줘야한다
System.out.println(e.getValue()+e.getKey()); //entry에 method를 이용해 정보를 가져온다
}

//generic을 이용해 미리 type을 설정할수있다
Set<Map.Entry<String, String>> set = tel.entrySet();  
Iterator<Map.Entry<String, String>> it = set.iterator(); 
while(it.hasNext()) {
Map.Entry e = it.next(); 

//미리 type이 설정되었기때문에 형변환을 해줄필요가 없다
System.out.println(e.getValue()+e.getKey());
}
-------------

//public class
//main
HashMap<String, String> tel = new HashMap<String, Integer>();
tel.put("seoul", "01");
tel.put("busan", "02");
tel.put("daegu", "03");

Set<Map.Entry<String, String>> set = tel.entrySet();

for(Map.Entry<String, String> e :set) {  
System.out.println(e.getValue()+e.getKey());
} //Map.Entry<String, String> type으로 set data를 e에 가져온다

'java' 카테고리의 다른 글

Generic  (0) 2019.08.04
이넘클래스(enum class)  (0) 2019.08.03
wrapper class  (0) 2019.08.03
Object class(toString(), Equals(), hashCode())  (0) 2019.08.03
예외처리(Exception)  (0) 2019.08.03

generic이란 class 내부에서 사용할 data type을 외부에서 지정하는 방법

//class Demo
public T data; 
//T type 의 data변수 선언, 꼭 T를 쓸필요는없다.
//main
Demo<String> d1 = new Demo<String>();
Demo<Integer> d2 = new Demo<Integer>();

//data type이 정해져있지않은 class를 이용해

//객체를 생성하면서 data type을 정한다
-----

//일반적인 class 사용하는 방법
//class Demo
public Integer data;
public void setData(Integer data) {
this.data = data;
}
public Integer getData() {
return data;
}

//public class
//main
Demo d1 = new Demo();

Integer ing = new Integer(100);
d1.setData(ing);
System.out.println(d1.getData());
------
//class GenericDemo
public T data;
public void setData(T data) {
this.data = data;
}
public T getData() {
return data;
}

//public class
//main
GenericDemo<Integer> gd = new GenericDemo<Integer>();
gd.setData(new Integer(200));
System.out.println(gd.getData());

//data type을 class가 아닌 여기서 설정할수있다

GenericDemo<String> gd1 = new GenericDemo<String>();
gd1.setData("hello");
System.out.println(gd1.getData());

//하나의 class로 여러 data type을 만들수있어서 효율적이다
-------
//class StudentData 
public String name;
StudentData(String name){
this.name = name;
} //생성자 생성
public String toString() {
return name;
}//주소값이 출력되기때문에 overriding해주거나 

//(p1.data.name)형태로 출력해줘야한다
//class Person <T,E>
public T data;
public E id;
Person(T data, E id){
this.data = data;
this.id = id;
} //생성자 생성

//generic class를 복수의 type으로 사용할경우 참조형을 사용해야한다

//public class

//main
Person<StudentData, Integer> p1 = 

new Person<StudentData, Integer> (new StudentData("jusung"), new Integer(20150000));
//person의 두개의 유형을 설정하고 객체를 생성한다

//복수의 type을 사용할경우 Reference type(참조형)만 가능하다 
System.out.println(p1.data+p1.id);

//data의 경우 주소값이 출력이되기때문에 toString method를 overriding해줘야한다
-------

//class StudentData 
public String name; 
StudentData(String name){ 
this.name = name; 
}
public String toString() { 
return name; 
}
//class Person <T,E>
public T data; 
public E id; 
Person(T data, E id){ 
this.data = data; 
this.id = id; 
} 

public <T> void getInfo(T data) { 
System.out.println(data); 
} //T type의 매개변수를받아서 method에 사용할수있다

//public class

//main 
Person p1 = new Person (new StudentData("jusung"), new Integer(20150000)); 
//두개의 매개변수를 이용해 type을 알수있기때문에

//<StudentData, Integer> 생략해줄수있다
System.out.println(p1.data+p1.id);

//toString을 overriding해줘서 사용하면된다


p1.<StudentData> getInfo(new StudnetData("jusung")); 


StudentData sd = new StudentData("jusung");
p1.getInfo(sd); //sd의 type을 알수있기때문에 generic type을 생략해도된다
---------

//Generic 제한

//class Data
public String getData() {
return "people data";
}

//class StudentData extends Data

public String name; 
StudentData(String name){ 
this.name = name; 
}
public String toString() { 
return name; 
}
//class Person <T extends Data>

//T를 Data의 class나 Data의 자식 class인

//StudentData만을 사용하겠다는뜻이다

public T data; 
Person(T data){ 
this.data = data; 
} 

public <T> void getInfo(T data) { 
System.out.println(data); 
} 

//public class

//main 

Person p1 = new Person("jusung");

----------

//interface 제한

//interface Data
int getData();

 

//class StudentData implements Data

public String name; 
StudentData(String name){ 
this.name = name; 
}

 

public int getData(){

return 20140002;

}//getData의 method를 overriding을 해준다


public String toString() { 
return name; 
}
//class Person <T extends Data>

//T를 Data의 interface나 Data class를 implements한

//StudentData만을 사용하겠다는뜻이다

 

public T data; 
Person(T data){ 
this.data = data; 
} 

public <T> void getInfo(T data) { 
System.out.println(data); 
} 

//public class

//main 

StudentData sd = new StudentData("jusung")

Person p1 = new Person(sd);

p1.getInfo(sd); //jusung이 출력된다

'java' 카테고리의 다른 글

Colletions framework(ArrayList, HashSet)  (0) 2019.08.04
이넘클래스(enum class)  (0) 2019.08.03
wrapper class  (0) 2019.08.03
Object class(toString(), Equals(), hashCode())  (0) 2019.08.03
예외처리(Exception)  (0) 2019.08.03

enumeration class는 열거형 클래스로 연관된 상수들의 집합이다
class 의 일종으로 생성자를 가질수있지만 접근제어자는 private형만 가능하다 
enum class도 일반클래스와 마찬가지로 컴파일할때 자동으로 생성자를만들어주지만
private이기때문에 생성자를 통하여 객체를 생성할수는없다
enum class 의 values() method를 호출하면 
enum class내에 선언되있는 모든 상수를 리턴한다.

 

//public class

public static final int PLATINUM_MEMBER = 1;  
public static final int LOYAL_MEMBER = 2;
public static final int GOLD_MEMBER = 3;  
public static final int SILVER_MEMBER = 4; 

//finall로 상수화시켜 더쉽게 이해할수있게한다

//상수가 많아질경우 복잡해질수있다

//main

int grade = GOLD_MEMBER; 
switch(grade) { 

case PLATINUM_MEMBER: 
System.out.println(30+"% discount"); 
break; 
case LOYAL_MEMBER: 
System.out.println(20+"% discount"); 
break; 
case GOLD_MEMBER: 
System.out.println(10+"% discount"); 
break; 
case SILVER_MEMBER: 
System.out.println(5+"% discount"); 
break; 

//이와같이 개발자 입장에서 이해하기쉽다

----------

interface A{ 
int PLATINUM_MEMBER = 1,LOYAL_MEMBER = 2,GOLD_MEMBER = 3,SILVER_MEMBER = 4; 
//상수가 많을경우 interface를 만들어서 더 단순하게 쓸수있다

//불러올때 앞에 interface명을 붙여줘야한다. ex(A.GOLD_MEMBER;)  

//public class

//main
int grade = A.GOLD_MEMBER; 
switch(grade) { 

case A.PLATINUM_MEMBER: 
System.out.println(30+"% discount"); 
break; 
case A.LOYAL_MEMBER: 
System.out.println(20+"% discount"); 
break; 
case A.GOLD_MEMBER: 
System.out.println(10+"% discount"); 
break; 
case A.SILVER_MEMBER: 
System.out.println(5+"% discount"); 
break; 

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

interface A{ 
int PLATINUM_MEMBER = 1,LOYAL_MEMBER = 2,GOLD_MEMBER = 3,SILVER_MEMBER = 4; 
//상수가 많을경우 interface를 만들어서 더 단순하게 쓸수있다

interface B{ 
int PLATINUM_MEMBER = 1,LOYAL_MEMBER = 2,GOLD_MEMBER = 3,SILVER_MEMBER = 4; 
//불러올때 앞에 interface명을 붙여줘야한다. ex(B.GOLD_MEMBER;) 

//A, B 두회사가 있을시 등급은 4등급으로 같지만 할인율이 다를수있다

//public class

//main

if(A.PLATINUM_MEMBER == B.PLATINUM_MEMBER) { 
System.out.println(" A,B의 할인율은 같다") 
//기본형인 int형을 비교하기때문에 error가 발생하지않지만

//runtime중 error가 발생할수있기 때문에 좋은방법이 아니다.
-------------

//interface내의 각각의 상수를 class로 설정할수있다

class A{ 
public static final A PLATINUM_MEMBER = new A(); 
public static final A LOYAL_MEMBER = new A(); 
public static final A GOLD_MEMBER = new A(); 
public static final A SILVER_MEMBER = new A(); 
} 
class B{ 
public static final B PLATINUM_MEMBER = new B(); 
public static final B LOYAL_MEMBER = new B(); 
public static final B GOLD_MEMBER = new B(); 
public static final B SILVER_MEMBER = new B(); 
//각각의 상수를 Class로 설정할경우 코드가 복잡해지고 

//A, B를 비교할때 error를 찾을수있지만 stitch문에 적용할수없다 

//public class

//main

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

//memR.GOLD_MEMBER형태로 불러온다 
//enum class를 사용할경우 관리하기가 간편해지고 switch문에도 적용이된다 

// class memR{ 
// public static final memR PLATINUM_MEMBER = new memR(); 
// public static final memR LOYAL_MEMBER = new memR(); 
// public static final memR GOLD_MEMBER = new memR(); 
// public static final memR SILVER_MEMBER = new memR(); 
// private memR() {} 
// } //enum class를 만들경우 이와같이 상수의 개수만큼

// 생성자가 호출이 되서 객체를 생성한다 

enum memR{ 
PLATINUM_MEMBER,LOYAL_MEMBER,GOLD_MEMBER,SILVER_MEMBER; 

//public class

//main

memR grade = memR.GOLD_MEMBER; 
switch(grade) { 
case PLATINUM_MEMBER: 
System.out.println(30+"% discount"); 
break; 
case LOYAL_MEMBER: 
System.out.println(20+"% discount"); 
break; 
case GOLD_MEMBER: 
System.out.println(10+"% discount"); 
break; 
case SILVER_MEMBER: 
System.out.println(5+"% discount"); 
break; 
} 
------------ 

//enum class안에 멤버나 method를 만들어 효율적으로 사용할수있다

//enum memR
PLATINUM_MEMBER(30),LOYAL_MEMBER(20),GOLD_MEMBER(10),SILVER_MEMBER(5);

//인자를 가진 생성자를 만들어줬기때문에 인자를 입력해주어야한다
int discount;
memR(int discount){
this.discount = discount;
}//생성자생성, 접근제어자로 private, default가 올수있다
public String getDiscount() {
return discount + "% discount";
}//method생성
//할인율이 변경될수 직접바꿔줘야한다는 단점이있지만 switch문보다 성능면에서 더좋다
//public class

//main
memR mm = memR.ROYAL_MEMBER;
System.out.println(mm); //royal member가 출력된다

 

String str = mm.getDiscount(); //값을 return받는 변수생성
System.out.println(str);
//loyal member 20% discount가 출력된다

for(memR marr : memR.values()) { //for each문으로 각각의상수들을 array에 저장한다
System.out.println(marr+marr.getDiscount());
//각각의 상수와 할인율을 출력할수있다

'java' 카테고리의 다른 글

Colletions framework(ArrayList, HashSet)  (0) 2019.08.04
Generic  (0) 2019.08.04
wrapper class  (0) 2019.08.03
Object class(toString(), Equals(), hashCode())  (0) 2019.08.03
예외처리(Exception)  (0) 2019.08.03

wrapper 클래스란 기본형을 객체로 사용하기위해 class로 정의한것을 말한다
더 다양한 기능을 사용하기위해 참조형으로 만든것이다

byte -> Byte

short -> Short

int -> Integer

long -> Long

float -> Float

double -> Double

char -> Character

boolean -> Boolean

 

//public class

//main
int a = 100; //연산하기위해서만 사용
Integer aa = new Integer(100);
Integer aa1 = new Integer("100");

//Integer aa에 100이란 숫자값과 문자값을 넣고 다양하게 사용할수있다 

System.out.println(aa.equals(aa1));
//wrapper class는 equals method를 overriding했기때문에 true값이 나온다 
System.out.println(aa.toString());
//wrapper class는 toString method를 overriding했기때문에 100이란 값이 나온다 

String str = 100;
int ii = Integer.parseInt(str); //Integer.parseInt()는 문자열을 정수형으로 바꿔준다
System.out.println(ii); //100이란 정수 값이 출력된다
int ii2 = ii + 100; //정수형으로 바꿧기때문에 error가 없다
System.out.pintln(ii2);

String str2 = Integer.toBinaryString(200); // toBinary는 숫자값을 문자열(string type)으로 반환해준다
System.out.println(str2); //이진수형태인 문자열로 출력

int ii3 = Integer.parseInt(str2, 2); //str2에 2진수값을 정수로 변환
System.outprintln(ii3); //정수 200이 출력된다

int ii4 = Integer.parseInt("100",8);
System.out.println(ii4); //100이라는 8진수를 10진수로 표현

Integer intg = new Integer(150);
int intg1 = intg.intValue(); 

//intValue method를 통해 Integer 객체를 기본 int형으로 변환한다
int j = intg1 + 100; //정수로 바꿧기때문에 성립이된다

 

//autoBoxing기능으로 자동으로 변환이된다

Integer intg = new Integer(150)
int k = 200;
int j = intg +10;
//Integer 객체를 기본 int형으로 바꾸지않아도

//자동으로 정수형으로 변환이되는걸 anautoBoxing이라고한다
Integer ing = 200; 
Integer ing = new Integer(200);

//아래와같이 autoBoxing처리가 자동으로 된다 

'java' 카테고리의 다른 글

Generic  (0) 2019.08.04
이넘클래스(enum class)  (0) 2019.08.03
Object class(toString(), Equals(), hashCode())  (0) 2019.08.03
예외처리(Exception)  (0) 2019.08.03
다형성(Polymorphism) -second  (0) 2019.08.03

Object class
최상위클래스로 모든클래스는
암시적으로 Object를 상속받고있다
-----
//public class ObjectEx extends Object

//입력하지않아도 암시적으로 extends Object 를 상속하고있다
//main
ObjectEx obj = new ObjectEx();
obj.toStringFunc(obj);
}

//toStringFunc

public void toStringFunc(ObjectEx obj) {
System.out.println(obj); 
//객체명만 들어갈경우 자동으로 toString method를 호출한다
System.out.println(toString()); 
//toString method는 해당class 객체를 문자열로 반환해주는 역할이다
//getClass().getName()+'@'+Integer.toHexString(hashCode())가 출력된다
System.out.println("hi"+this); //this는 해당class obj를 의미한다
} //객체에 문자열 +연산을하는경우 toString()method가 자동으로 호출된다

 
public String toString() {

//toString 은 복잡하게출력되므로 알기쉽게 overriding을해서 사용한다

return "this is ObjectEx class";
}
------

//public class

//main
int aa = 100;
int bb = 100;

 

if(aa==bb) { 
System.out.println("aa와 bb는 서로같다"); 
}else { 
System.out.println("aa와 bb는 서로 다르다"); 
} //== 비교연산자는 기본자료형을 비교하는경우 값을 비교하기때문에

//서로 같다라는 내용이 출력된다


String str1 = new String("heelo");
String str2 = ("heelo");

 

if(str1==str2) { 
System.out.println("str1, str2는 같다"); 
}else { 
System.out.println("str1, str2는 다르다"); 
} //== 비교연산자는 참조형(Reference Type)을 비교할경우

//주소값을 비교하기때문에 서로 다르다라는 내용이 출력된다.

//만약에 str1=str2; 를한다면 주소값이 같아지기때문에 같다가 출력된다. 

 

//equals는 앞의객체와 뒤의객체를 비교해 true, false값을 반환한다
if(str1.equals(str2)) { 
System.out.println("str1, str2는 같다");
}else { 
System.out.println("str1, str2는 다르다");
} //String 객체는 Object class에 있는 equals method를 

//overriding을해서 비교하기때문에 '다르다'가출력된다 

//String 객체의 Equals method는 overriding된 method여서 내용을 비교한다


value va1 = new Value(10);
value va2 = new Value(10); //서로 다른 instance를 가리킨다

if(val1.equals(var2)) {
System.out.println("va1과 va2는 서로같다");
}else { 
System.out.println("va1과 va2는 서로 다르다");
} //Value class는 overriding을 하지 않아서 서로 "다르다"가 출력된다 

//va1 = va2;를 입력할경우 "같다"가 출력된다

//Equals method가 Objet class 에 있는경우 주소값을 비교한다

 

//hashCode는 주소의 값을 반환해주는 method이다

System.out.println(str1.hashCode()); 
System.out.println(str2.hashCode()); //같은 값이 출력된다 
//서로다른주소의 값이 나와야하지만 내용이 같은경우 

//String 객체에서는 hashCode의 값이 같아지도록 overriding을했다  

 

System.out.println(va1.hashCode()); 
System.out.println(va2.hashCode()); //다른값이 출력된다

//class Value
int a;
public Value(int a) {
this.a = a;
}


// public boolean equals(Object obj){
// if(obj != null && obj instanceof Value) {
// return a == ((Value)obj).a;
// }else {
// return false;
// } //내용을 비교할경우 이와같이 overriding을 해줘야 "같다"가 출력된다.
// } //String형태도 이와같이 overriding되서 사용되고있다 

'java' 카테고리의 다른 글

이넘클래스(enum class)  (0) 2019.08.03
wrapper class  (0) 2019.08.03
예외처리(Exception)  (0) 2019.08.03
다형성(Polymorphism) -second  (0) 2019.08.03
다형성(Polymorphism) -first  (0) 2019.08.03

예외처리란 프로그램 실행시 발생할수있는 상황들을 미리 정해놓고

예외가 발생했을경우에 대비하여 코드를 작성하여

프로그램이 정상적으로 작동하게하기위해서다.

 

컴파일 에러는 컴파일할때 발생하는 에러로 문법상의 오류를 말한다

런타임 에러는 컴파일후 실행할때 발생하는 에러이다

런타임 에러는 error와 exceptiond으로 나눌수있는데

error는 코드에서 처리할수없는 심각한오류를말하고

exception은 코드에서 처리할수있는 가벼운 오류를 말한다

 

exception 에는 IOException, ClassNotFoundException, RuntimeException등이 있는데

IOException과 ClassNotFoundException은 사용자의 입력 실수에 의해 오류가 발생하는 경우이다

IOException과 ClassNotFondException경우 컴파일시 예외처리를 해줘야한다

 

RuntimeException에는 ArithmeticException, NullPointerException, IndexOutOfBoundsException

등이 있는데 개발자에의해 오류가 발생하는 경우이다


직접처리
try {
예외발생 예상코드
}cath(해당 예외 클래스 e){
예외처리 코드
}
선언처리
public void aaa() throws IOException{
int i = System.in.read();
//aaa()를 호출하면 IOException class도 같이호출되

//입력시 발생할지도모를 오류를 해결한다 
----------

//public class

//main
int intArray[] = {1,2,3,4,5}; 
//변수를 try 안에서 선언하면 지역변수가되서 사라지게되기때문에 밖에서 선언해줘야한다

try {
System.out.println(intArray[0]);//공간이 하나이므로 1출력
System.out.println(intArray[5]);//공간이 6개이므로 에러
}catch(Exception e) {
    System.out.println("예외발생");

}finally {

    System.out.println("항상 실행되어야될 코드");
} //finally는 반드시 수행되는부분이다 

//return이 있을경우 다음 문장을 수행하지않고 blcok을 빠져나오게되는데 
//finally가 있으면 중간에 return이 있어도 반드시 수행된다 
//주로 DB접속을 끈을때 사용한다 
--------

//public class

//main
int intArray[] = {1,2,0,4,5};

try {
System.out.println(intArray[0]); //첫번째 배열 1이 출력
System.oot.println(intArray[4]/intArray[2]); 

//세번째 배열값 0으로 나눌수없으므로 error발생

System.out.println(intARray[5]); //배열이 6개가 아니므로 error발생

String str = null;  
str.toString(); 

//toString은 문자열을 출력하는 method인데 str은 null값이므로 error발생 

}catch(ArithmeticException e) {
    System.out.pintln(e.getMessage()); 

}catch(ArrayIndexOutOfBoundsException e) {
    System.out.println(e.toString()); 

//발생할수있는 예상 코드가 여러개일경우 다중 catch문을 사용한다

}catch(Exception e) {

//예상치 못한 error를 상위class의 Exception을 입력
//Exception이 상위의 class이므로 가장 마지막에 적어줘야 하위class의 error check가 실행된다.    

    e.printStackTrace(); 

}System.out.println("항상 실행되어야할 코드"); 

//e.getMessage()를하면 에러설명을볼수있다

//e.toString()을 쓰면 자세한 에러설명을해준다

//e.printStackTrace();를 입력할경우 더 자세한 에러설명을 해준다 
-----

//public class

//main
ThrowEx a = new ThrowEx();
a.throwSample(12); //10보다 크므로 error message 를 출력한다

//class ThrowEx
public void throwSample(int n) {

//예외를 발생시켰으므로 try, catch를 이용하여 처리를해야한다
try {  
if(n > 10) { 
throw new Exception("n 값이 10보다 크다");

//throw는 문자를이용해 예외를 발생시키겠다는 의미이다 
}}catch(Exception e) {
     e.printStackTrace();

}
------

//public class

//main

ThrowEx a = new ThrowEx();
try {
a.throwSample(12);
}catch(Exception e) {e.printStackTrace();}

//throws Exeption을 가진 method를

//호출했기때문에 try,catch문으로 처리를해줘야한다

//class ThrowEx
public void throwSample(int n) throws Exception{  
if(n > 10) { 
throw new Exception("n 값이 10보다 크다");
}} //throws Exeption은 예외를 호출한쪽으로 던진다는의미로 
//이 method를 호출할때 예외처리를 해줘야한다는뜻이다
------

//public class

//main

ThrowEx a = new ThrowEx();
try {
a.throwSample(12);
}catch(Exception e) {

e.printStackTrace();

}

//class ThrowEx
public void throwSample(int n) throws IllegalArgumentException,IOException{
//예외발생이 2개일때 여러개의 예외를 호출하는 쪽으로 넘겨줌으로써 처리할수있다 

//try,catch문을 중첩되게 사용해서 IOException을 처리할수도있고

//Exception을 넘겨줄때 IllegalArgumentExeption,IOException을 같이 넘겨줄수도있다

try {
int aa = System.in.read(); //입력받을땐 IOException처리를 해줘야한다
System.out.println(aa); //a를 입력할경우 아스키값 97이출력
}catch(IOException e) {
e.printStackTrace();
}//try,catch문으로 예외처리를 할수있고

//try,catch문 없이 throws로 여러개의 예외를 한번에넘겨줄수있다
if(n > 10) {
throw new IllegalArgumentException("n 값이 10보다 크다");
}}
------

//public class

//main

MyException mye = new MyException(); 

//method에서 예외처리를 하지않았으므로 여기서해줘야한다
try {
mye.IOExc();
}catch(IOException e) {
e.printStackTrack();
//throws나 try,catch문 둘중하나를 입력해 예외처리를 해줘야한다

 

//class MyException
void ArithmeticExc() {
throw new ArithmeticException();
//실행을해봐야 알수있으므로 예외처리를 하지않는다

 

void IOExc() {
throw new IOException();
} //컴파일시 예외처리를 하라고 강요되어진다

 

void IOExe1() {
try {
throw new IOException()
} cath (IOException e){
e.printStackTrace();
} //미리 IOException처리를 해주어야한다
------

//public class

//main

Divide di = new Divide(); 
di.setNumber(5, 0);
try {
di.divide(); //0으로 나누기때문에 error가 생긴다
}catch(MyException e) {
e.printStackTrace();
System.out.println(e.getMessage());
//exception!: can not divide by zero 가 출력된다
//method에서 발생한 예외를 try,catch문을 이용해 처리한다 

//class Divide
int n1, n2;
public void setNumber(int n1, int n2) {
this.n1 = n1;
this.n2 = n2;
}
public void divide() {
if(this.n2 == 0) {
throw new MyException("exception!: can not divide by zero");
} //0일경우 Myexception을 호출해 예외를 발생시켜준다 
System.out.println(this.n1/this.n2);
}


//class MyException extends Exception
public MyException() {
super(); //부모의 기본생성자 호출
//생성자를 만들어준다
public MyException(String msg) {
super(msg);
//생성자를 overriding해준다

'java' 카테고리의 다른 글

wrapper class  (0) 2019.08.03
Object class(toString(), Equals(), hashCode())  (0) 2019.08.03
다형성(Polymorphism) -second  (0) 2019.08.03
다형성(Polymorphism) -first  (0) 2019.08.03
인터페이스(interface)  (0) 2019.08.03

//public class 

public static void exe(Calculator cal){

//static으로 class method 생성해 각각의 instance가 method를 공유한다

//부모타입으로 매개변수를생성해 data를 가져온다

cal.setNum(100,200); 
cal.calResult(); 

//main
public static void main(String[] args) {
Calculator c1 = new Sum(); //부모type의 자식 instance를 생성
Calculator c2 = new Subtractor(); 

exe(c1); //sum 의 값을 출력한다
exe(c2); //subtractor의 값을 출력한다

//부모타입으로 매개변수를 받기때문에 각각의 인스턴스는 인자값을 받아온다

//이처럼 calculator 하나의 type 으로 기능이 다른동작을수행하는걸 다형성이라고한다 


Sum sum = new Sum();
sum.setNum(100,200);
sum.calResult();

Subtractor sub = new Subtractor();
sub.setNum(100,200);
sub.calResult();

 

//abstract class Calculator 

//abstract는 미완성클래스로 상속을 강요하는 class이다
int n1, n2;

public void setNum(int n1, int n2) {
this.n1 = n1;
this.n2 = n2;
}
public abstract void calResult(); 

//추상method는 overriding을 해줘야한다

//class Sum extends Calculator
public calResult(){ 
System.out.println(this.n1+this.n2);
//추상method를 overriding해준다

 

//class Subtractor extends Calculator
public void calResult() {
System.out.println(this.n1-this.n2;)
} //추상method를 overriding해준다
----------

Calculator c1 = new Sum(); 
Calculator c2 = new Subtractor();


Calculator ca[] = new Calculator[2]; 
ca[0] = new Sum(); 
ca[1] = new Subtractor(); 
//서로 다른 객체를 이용해서 method를 호출할수있지만

//부모가 같을경우 배열을 이용하여 두객체를 하나의 객체로 선언할수있다

-----------

static int i = 0; //carArray가 static이기때문에 변수도 static으로 바꿔준다
static Calculator calArray[] = new Calculator[3];

//static으로 배열을 생성했기때문에 객체를생성할필요가없다

//public class

public static void exe(Calculator cal){

//static으로 class method 생성해 각각의 instance가 method를 공유한다

//부모타입으로 매개변수를생성해 data를 가져온다

calArray[i++] = cal;

//carArray배열에 car객체를 입력한다

cal.setNum(100,200); 
cal.calResult(); 

} //class method

//main
Sum sum = new Sum();  
Subtractor sub = new Subtractor(); 

 

exe(sum); 
exe(sub); 
exe(sum); 
exeSequence(); 

//같은 class이므로 바로불러올수있다

 

//exeSequence
public static void exeSequence() {
for(int i=0;i<calArray.length;i++) {
String str = calArray[i].operand();

//carArray[i]에 operand method를 호출
System.outprintln(str);
} //연산의 순서를 나타내기위한 class method

//abstract class Calculator 

//abstract는 미완성클래스로 상속을 강요하는 class이다
int n1, n2;

public void setNum(int n1, int n2) { 
this.n1 = n1; 
this.n2 = n2; 
} 
public abstract void calResult(); 

//추상method는 overriding을 해줘야한다 

public abstract String operand();

//연산의 순서를 나타내기위해 추상method를 만든다


//class Sum extends Calculator
public calResult(){ 
System.out.println(this.n1+this.n2); 
//추상method를 overriding해준다

public String operand(){

return "plust";

//추상method를 overriding해준다

 

//class Subtractor extends Calculator
public void calResult() { 
System.out.println(this.n1-this.n2;) 
} //추상method를 overriding해준다

public String operand(){

return "minus";

//추상method를 overriding해준다

'java' 카테고리의 다른 글

Object class(toString(), Equals(), hashCode())  (0) 2019.08.03
예외처리(Exception)  (0) 2019.08.03
다형성(Polymorphism) -first  (0) 2019.08.03
인터페이스(interface)  (0) 2019.08.03
final class, final method  (0) 2019.08.02

다형성이란 하나의 method나 class가 다양한 방법으로 동작하는것을말한다

하나의 참조변수로 여러타입의 객체를 참조할수있는것
즉 조상타입의 참조변수로 자손타입의 객체를 다룰수있는것이 다형성이다

조상타입의 참조변수로 자손타입의 인스턴스를 참조할수있지만
자손타입의 참조변수로 조상타입의 인스턴스를 참조할수없다.


//public class
//main
Super sp = new Super(); 
System.out.println(sp.x +sp.y);
sp.ss(); //일반적인 방법

Child ch = new Child();
System.out.println(ch.z+ch.j);
ch.getClass(); //일반적인 방법

//super type으로 참조변수로 child instance생성 
Super sp1 = new Child(); 
System.out.println(sp1.x+sp1.y); //super class내에 있어서 가능
System.out.println(sp1.z+sp1.j);  //참조할수 없다
//부모타입으로 자식인스턴스를 생성할경우 자식이가진 고유한 멤버는 접근할수없다
sp1.ss(); //super class에 method가 child class 에서 overriding된게 출력된다

//overriding이 됬을경우 overriding이 된 method를 우선순위로 출력한다
Child ch1 = new Super(); //자식타입의 참조변수는 부모인스턴스를 생성할수없다

//class Super
int x=200;
int y=200;
public void ss() {
System.out.println("parents class");
}

//class Child extends Super
int z = 1000;
int j = 2000;
public void ss() {
System.out.println("child class");
} //overriding해서 super class의 method를 재정의

참조변수의 형변환
서로 상속관계에 있는 타입간의 형변환만 가능하다
자손타입에서 부모타입으로 UpCasting 인경우 형변환생략 가능
부모타입에서 자손타입으로 DownCasting 인경우 형변환 생략 불가

참조변수의 형변환은 참조변수의 타입을 변환하는것으로 인스턴스에 영향을 주는것이 아니다.
참조변수의 형변환은 참조하고 있는 인스턴스에서 사용가능한 멤버의 개수를 조절하는 것이다.

 

//public class
//main
Car car = null;

FireEngine fe = new FireEngine(); //객체생성
fe.water(); //method 호출
Truck tr = new Truck();
tr.sand();


fe = (FireEngine)tr; 

//상속관계가 아니기때문에 tr을 FireEngine으로 형변환을할수없다

car = (Car)fe; //자식(fe)를 부모타입(Car)로 변환하는 upCasting으로 (Car) 생략가능 
car.water(); //자식 고유의 method로 사용할수없다

fe = (FireEngine)car; //부모타입(car)를 자식(FireEngine)으로 downCasting으로 (FireEngine) 생략불가 
fe.water(); //car의 null 값에 car=(Car)fe;를 했기때문에

//fe=(FireEngine)car은 결국 자기자신을 가리키게 되므로 실행이된다

//class Car
String color;
int door;

public void accel() {
System.out.println("dirve");
}
public void break() {
System.out.println("stop");
}

//class FireEngine extends Car
void water() {
System.out.println("water");
}

//class Truck extends Car
void sand() {
System.out.println("take sands");
}

----------

//class Car
String color;
int door;

public void accel() {
System.out.println("dirve");
}
public void break() {
System.out.println("stop");
}

//class FireEngine extends Car
void water() {
System.out.println("water");
}

//class Truck extends Car 
void sand() {
System.out.println("take sands");
}

//public class
//main 
Car car = new Car(); //car instance생성
Car car2 = null;
Truck tr = null; //tr이라는 참조변수는 null값을 가진다 

car.accel(); //drive 출력

//car 참조변수는 car instance를 가리키고있고 car instance내 method에 접근가능하다 

 

tr = (Truck)car; //자식 참조변수는 부모의 인스턴스를 참조할수없으므로 error가 난다
tr.accel(); //error가 난다


car2 = (Car)tr; //upCasting으로 (Car)생략가능
car2.accel(); //tr값이 null이기때문에 car2가 null값을 참조한것으로 error가 생긴다

instanceOf
참조변수가 참조하고있는 인스턴스의 실제타입을 알아보는 연산자로
연산결과로 boolean값 true, false를 리턴한다.
if(a instanceOf Car) 참조변수 a가 Car타입인지를 true, false값으로 return 

//public class

//main

Truck tr = new Truck();

if(tr instanceof Truck) {  
System.out.println("it is truck");
} //true값이 출력된다


if(tr instanceof Car) {  
System.out.println("it is car");
} //car는 truck의 부모로 true값 출력


if(tr instanceof Object) { 
System.out.println("it is Object");
} //object는 모든클래스의 부모로 true값 출력 

'java' 카테고리의 다른 글

예외처리(Exception)  (0) 2019.08.03
다형성(Polymorphism) -second  (0) 2019.08.03
인터페이스(interface)  (0) 2019.08.03
final class, final method  (0) 2019.08.02
추상클래스(abstract class), 추상메소드(abstract method)  (0) 2019.08.02

+ Recent posts