선택자를 이용하여 원하는 HTML요소를 선택하고 , 동작함수를 정의하여 선택된 요소에 원하는 동작을 설정한다.
* $() 함수
$() 함수는 선택된 HTML요소를 제이쿼리에서 이용할 수 있는 형태로 생성해 주는 역할을 한다.$() 함수의 인수로는 HTML 태그 이름뿐만 아니라, CSS 선택자를 전달하여 특정 HTML 요소를 선택할 수 있음.이러한 $() 함수를 통해 생성된 요소를 제이쿼리 객체(jQuery object)라고 하며, 생성된 제이쿼리 객체의 메서드를 사용하여 여러동작을 설정할 수 있다.
* Document 객체의 ready() 메서드 (예제1215_2)
자바스크립트 코드는 웹 브라우저가 문서의 모든 요소를 로드 한 뒤에 실행되어야 합니다.
보통은 별다른 문제가 바생하지 않지만, 다음과 같은 경우에는 오류가 발행 합니다.
- 아직 생서되지 않은 HTML요소에 속성을 추가하려고 할 경우
- 아직 로드되지 않은 이미지의 크기를 얻으려고 할 경우
* Window 객체의 onload() 메서드 (예제1215_2)
자바스크립트에서는 Window 객체의 onload()메소드를 이용하여 문서가 모두 로드된 뒤에 코드가 실행되도록 설정
문법)
window.onload = function(){
자바스크립트 고드;
};
* 제이쿼리에서는 Document객체의 ready()메서드를 이용하여 같은 결과를 보장 (예제1215_2)
문법)
$(document).ready(function(){
제이쿼리 코드;
});
* jQuery Team에서는 같은 결과를 보장하는 더욱 짧은 문법을 다음과 같이 제공 (예제1215_2)
/* 문제)과목 점수를 입력을 받아 학점을 출력하는 프로그램 과목점수는 0~100점 이며, 범위가 초과되면 "0~100점 사이 값을 입력하세요." 라고 화면에 출력. (화면에 출력 document.write 사용) 과목점수가 정상 입력되었을 경우. 90~100 : A, 80~89 : B, 70~79 : C, 60~69 : D, 나머지 : F 로 학점(grade)를 구하고 A인 경우 "잘했습니다." B인경우 "잘했습니다." C인 경우 "조금만 노력하면 잘 할수 있습니다." D인 경우 "좀 더 노력하세요" F인 경우 "많이 노력하기 바랍니다." 입력예)과목점수를 입력하세요. 85 출려계)잘했습니다. 당신의 학점은 B입니다. (단, B는 <b>태그 이용) 단, 출력은 document.write로 사용. */
/* 문제)커피를 주문하는 과정 중 어떤 커피를 주문 할 지 입력을 받은 후 출력하는 프로그램 입력예)무슨 커피 드릴까요? 아이스아메리카노 출력예)아이스아메리카노 1500월 입니다. 단, 아이스아메리카노(icecoffee) : 1500 카페라떼 : 4500 바닐라라떼 : 5500 나머지는 '000은(는) 없습니다.' 출력시 금액이 있는 경우가 정상적인 경우로 판다. */
* 1212_2 문제 2 (요일별 영업) *
/* 문제)요일을 입력받아 정상영업인지 휴무일인지 알려주는 스크립트 구현. 입력은 prompt()함수 사용. 월화수목금은 정상영업, 토일은 휴무라고 출력 입력예)요일을 입력하세요. 화 출력예)화요일은 정상영업 단, 출력을 switch문에서 처리. ...요일은 정상영업 / ...요일은 휴무 / ...은 요일이 아닙니다. */
** 1212_2 문제 3 (성적) **
/* 문제)성적 A~F 값을 입력 받아 출력. 입력예)성적을 입력하세요. a 출력예)아주 잘했습니다. 단, 성적입력은 A,B,C,F에 대해서만 처리하며 성적은 무조건 대문자로 처리하게 함. (대문자 변환 함수 : 변수명.toUpperCase()) 입력변수 grade 한개만 사용하여 처리. A : 아주 잘했습니다., B : 좋은 점수군요., C : 조금 더 노력하세요. , F : 다음 학기 수강하세요. 나머지 : 알 수 없는 학점입니다. 메세지 출력은 alert으로 처리. */
* 소스 1212_2 *
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>제어문(switch)</title>
</head>
<body>
<script>
var day;
var week = new Date().getDay(); //0(일요일)~6(토요일)
/*
switch(week){
case 0:
day = "일요일";
break;
case 1:
day = "월요일"; break;
case 2:
day = "화요일";
break;
case 3:
day = "수요일";
break;
case 4:
day = "목요일";
break;
case 5:
day = "금요일";
break;
case 6:
day = "토요일";
break;
default:
day = "없는 요일";
}
document.write("<h1>오늘은 <b>" + day + "</b>입니다.<h1");
*/
/* 1
문제)커피를 주문하는 과정 중 어떤 커피를 주문 할 지 입력을 받은 후 출력하는 프로그램
입력예)무슨 커피 드릴까요?
아이스아메리카노
출력예)아이스아메리카노 1500월 입니다.
단, 아이스아메리카노(icecoffee) : 1500
카페라떼 : 4500
바닐라라떼 : 5500
나머지는 '000은(는) 없습니다.'
출력시 금액이 있는 경우가 정상적인 경우로 판다.
var type = prompt("무슨 커피 드릴까요?");
var price="";
//var price="" 초기값을 세팅하지 않으면 if(price != undefined) 또는 0으로 세팅 후 (price != 0)으로 가능
switch(type){
case ("아이스아메리카노"):
case ("icecoffee"):
price = 1500;
break;
case "카페라떼":
price = 4500;
break;
case "바닐라라떼":
price = 5500;
break;
default:
document.write(type + "은(는) 없습니다.");
}
if(price != ""){document.write(type + " " + price + "원 입니다.");}
*/
/* 2
문제)요일을 입력받아 정상영업인지 휴무일인지 알려주는 스크립트 구현.
입력은 prompt()함수 사용.
월화수목금은 정상영업, 토일은 휴무라고 출력
입력예)요일을 입력하세요.
화
출력예)화요일은 정상영업
단, 출력을 switch문에서 처리.
...요일은 정상영업 / ...요일은 휴무 / ...은 요일이 아닙니다.
var day = prompt("요일을 입력하세요.");
switch(day){
case '월':
case '화':
case '수':
case '목':
case '금':
document.write(day + "요일은 정상영업");
break;
case '토':
case '일':day
document.write(day + "요일은 휴무");
break;
default:
document.write(day + "은 요일이 아닙니다.");
}
*/
/* 3
문제)성적 A~F 값을 입력 받아 출력.
입력예)성적을 입력하세요.
a
출력예)아주 잘했습니다.
단, 성적입력은 A,B,C,F에 대해서만 처리하며 성적은 무조건 대문자로 처리하게 함.
(대문자 변환 함수 : 변수명.toUpperCase())
입력변수 grade 한개만 사용하여 처리.
A : 아주 잘했습니다., B : 좋은 점수군요., C : 조금 더 노력하세요. , F : 다음 학기 수강하세요.
나머지 : 알 수 없는 학점입니다.
메세지 출력은 alert으로 처리.
*/
var grade = prompt("성적을 입력하세요.");
grade = grade.toUpperCase(); //var grade = prompt("성적을 입력하세요.").toUpperCase();
switch(grade){
case 'A':
alert("아주 잘했습니다.");
break;
case 'B':
alert("좋은 점수군요.");
break;
case 'C':
alert("조금 더 노력하세요.");
break;
case 'F':
alert("다음 학기 수강하세요");
break;
default:
alert("알 수 없는 학점입니다.");
}
</script>
</body>
</html>
** 1212_3 문제 (숫자 맞추기 게임)**
* <head>에 함수 정의 해보기 *
<body> <h1>숫자 맞추기 게임</h1> 이 게임은 컴퓨터가 생성한 숫자를 맞추는 게임입니다. 숫자는 1부터 100사이에 있습니다.<br /> 숫자 : <input type="text" id="user" size="5" /> <input type="button" value="확인" onclick="guess()" /><br /> 추측 횟수 : <input type="text" id="guesses" size="5"> 힌트 : <input type="text" id="result" size="16" /> </body>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>숫자 맞추기 게임</title>
<script>
/*
입력값이 낮을 경우는 '낮습니다.', 높을 경우는 '높습니다.', 맞은 경우는 '성공입니다.'
*/
var computerNumber = 53;
var nGuessess = 0;
var cnt = 0;
//myNumber = document.getElementById("user").value;
//-> 헤드가 먼저 실행되기 때문에 document.getElementById("user").value 아직 없다. 따라서 바디 안의 무언가 가지고오려면 함수 안에서 하는 것이 좋다.
function guess(){
if(cnt==1){nGuessess=0; cnt=0;}
var result = "";
myNumber = document.getElementById("user").value;
nGuessess++; //어떤 경우든 시도는 한 것이기에 확인버튼 누를 시 증가하도록 후 맨 아래에 값 대입
if(myNumber < computerNumber){
result = myNumber + "보다 높습니다..";
alert("틀렸습니다.");
document.getElementById("user").value = "";
document.getElementById("user").focus();
}
else if(myNumber > computerNumber){
result = myNumber + "보다 낮습니다..";
document.getElementById("user").focus();
alert("틀렸습니다.");
document.getElementById("user").value = "";
document.getElementById("user").focus();
}
else if(myNumber == computerNumber){
result = "성공입니다!";
cnt=1;
}
else{
document.getElementById("result").value = '숫자를 입력하세요';
alert("숫자를 입력하세요.");
document.getElementById("user").value = "";
document.getElementById("user").focus();
}
document.getElementById("guesses").value = nGuessess;
document.getElementById("result").value = result;
}
</script>
</head>
<body>
<h1>숫자 맞추기 게임</h1>
이 게임은 컴퓨터가 생성한 숫자를 맞추는 게임입니다. 숫자는 1부터 100사이에 있습니다.<br />
숫자 : <input type="text" id="user" size="5" />
<input type="button" value="확인" onclick="guess()" /><br />
추측 횟수 :
<input type="text" id="guesses" size="5">
힌트 : <input type="text" id="result" size="16" />
</body>
</html>
* 반복문 : 같은 명령을 일정횟수만큼 반복하여 수행하도록 제어하는 실행문
while 문
do / while 문
for문
for / in 문
for / of 문
cf) 하나의 태그에 열고닫고 <br /> <input />
** 문제 1212_5 (구구단표 작성해보기) **
** 문제 1212_6 (prompt / innerHTML 두가지로 구구단 출력해보자) **
/* 문제) 구구단을 작은 수와 큰 수 순서로 입력받아 구구단 출력하는 프로그램 입력예)시작단을 입력하세요.2 끝단을 입력하세요.3 출력예)2단 2 * 1 =2 ... 2 * 9 = 18
3단 3 * 1 = 3 ... 3 * 9 = 27 단, 입력받은 값은 숫자로 변환함. 1. prompt 사용하여 구구단출력 2. html imput=text에서 입력받아 버튼 클릭시 구구단 출력 시작단 : num1 , 끝단 : num2 버튼 클릭시 호출함수는 gugu() <p id="tab"></p> : 이부분에 구구단 출력 */
* 방법1
* 방법 2
→방법2 <head>
<script> 속 함수
* 소스
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>반복제어문</title>
<script>
/*
문제) 구구단을 작은 수와 큰 수 순서로 입력받아 구구단 출력하는 프로그램
입력예)시작단을 입력하세요.2
끝단을 입력하세요.3
출력예)2단
2 * 1 =2
...
2 * 9 = 18
3단
3 * 1 = 3
...
3 * 9 = 27
단, 입력받은 값은 숫자로 변환함.
1. prompt 사용하여 구구단출력
2. html imput=text에서 입력받아 버튼 클릭시 구구단 출력
시작단 : num1 , 끝단 : num2 버튼 클릭시 호출함수는 gugu()
<p id="tab"></p> : 이부분에 구구단 출력
*/
function gugu(){
var i,j;
var result = ""; //누적하려면 초기값 세팅해줘야한다.
var n1 = document.getElementById("num1").value;
var n2 = document.getElementById("num2").value;
for(i = n1; i<=n2 ; i++){
result += "<br />" + i + "단<br />";
for(j=1 ; j<10 ; j++){
result += i + ' * ' + j + " = " + i*j + "<br />"
}
}
/*
//위의 포문과 같은 방법
for(i=n1 ; i<=n2 ; i++){
document.getElementById("tab").innerHTML += "<br ?>" + i + "단<br />";
for(j=1 ; j<10 ;j++){
document.getElementById("tab").innerHTML += i + ' * ' + j + " = " + i*j + "<br />";
}
}
*/
// document.getElementById("tab").innerHTML = result;
}
</script>
</head>
<body>
<!-- 방법1. -->
<!-- <script>
num1 = parseInt(prompt("시작단을 입력하세요."));
num2 = parseInt(prompt("끝단을 입력하세요."));
var i,j;
for(i = num1; i<=num2 ; i++){
document.write("<br />" + i + "단<br />");
for(j=1 ; j<10 ; j++){
document.write(i + ' * ' + j + " = " + (i*j) + "<br />");
}
}
</script> -->
<!-- 방법2 -->
시작단을 입력하세요. <input type="text" name="num1" id="num1" size="3" >
끝단을 입력하세요. <input type="text" name="num2" id="num2" size="3">
<input type="button" name="chk" onclick="gugu()" value="확인" /><br />
<p id="tab">여기에 innerHTML을 이용해 구구단출력을 해요(덮어쓰기)</p>
</body>
</html>
** 문제 1212_7 (3의 배수를 제외한 숫자 출력_continue / continue사용 x) **
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>연산자</title>\
<script>
function over(obj){
obj.src = "./img/computer2.jpeg" ;
}
function out(obj){
obj.src = "./img/computer1.jpeg";
}
</script>
</head>
<body>
<!--연산자-->
<h1>연산자</h1>
<script>
var x = 3, y = 5;
var a = "abc", b = "bcd";
document.write((x > y) + "<br />"); //false
document.write((a <= b) + "<br />"); //true(알파벳 a보다 b가 큼. 변수 맨 앞자리부터 체크)
document.write((x < a) + "<br />"); //false(숫자와 문자열 비교 불가)
x = 3, y = '3', z = 3;
document.write((x == y) + "<br />"); //true(값이 같으므로)
document.write((x === y) + "<br />"); //false(값은 같으나 타입이 다르므로)
document.write((x === z) + "<br />"); //true(값과 타입이 같으므로)
</script>
<br /><br />
<h1>delete 연산자</h1>
<script>
var arr = [1,2,3];
document.write("삭제 전 : " + arr + "<br />");
delete arr[2];
document.write("삭제 후 : " + arr + "<br />");
document.write("arr[2] : " + arr[2] + "<br />");
document.write("arr.length : " + arr.length + "<br />");
</script>
<br />
<h2><a href="javascript:void(0)">링크는 동작하지 않습니다.</a></h2>
<h2><a href="javascript:void(document.body.style.backgroundColor='yellow')">링크는 동작하지 않지만 HTML문서 배경은 변경됨.</a></h2>
<br /><br />
<!--이벤트 리스너 속성-->
<h3>이미지 위에 마우스를 올려 보세요.</h3>
<img src="./img/computer1.jpeg" alt="컴퓨터1" width="300" height="200" onmouseover="this.src='./img/computer2.jpeg'" onmouseout="this.src='./img/computer1.jpeg'" />
<br /><br />
<!--(head의)자바스크립트 함수 호출-->
<h3>이미지 위에 마우스를 올려 보세요.2</h3>
<img src="./img/computer1.jpeg" alt="컴퓨터2" width="300" height="200" onmouseover="over(this)" onmouseout="out(this)" />
</body>
</html>
→ 마우스 올리면 computer2로 이미지 바뀜
** 제어문 **
- 프로그램의 순차적인 흐름을 제어해야 할 때 사용하는 실행문, 제어문에는 조건문과 반복문.
- 조건문 : if 문 / if else 문 / else if 문/ else문 / switch 문
문법 ) if(표현식){ 표현식의 결과가 참일 때 시행하고자 하는 실행문; }
if(표현식){ 표현식의 결과가 참일 때 시행하고자 하는 실행문; }
else{ 표현식의 결과가 참일 때 시행하고자 하는 실행문; }
if(표현식1){ 표현식1의 결과가 참일 때 시행하고자 하는 실행문; }
else if(표현식2){ 표현식2의 결과가 참일 때 시행하고자 하는 실행문; }
else{ 표현식의 결과가 참일 때 시행하고자 하는 실행문; }
** 1211 (예제/문제/문제/문제) **
/ /trim() : 공백제거
** 1211_2 (문제/문제) **
* 위 문제의 cal 함수를 .js 파일로 빼서 사용해보기
-> 원래있던 cal 함수 주석처리 후
<scriptsrc="./js/sample2.js"></script> 입력하면 같은 결과 나옴다.
* 소스 코드
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>자바스크립트-제어문</title>
<script>
function cal(){
}
</script>
</head>
<body>
<script>
/* 1
문제) prompt()함수를 이용하여 점수를 입력받아 if~else를 사용하여 A~F까지 학점을 출력하는 스크립트 코드작성.
입력예) 점수를 입력하세요.
90
출력예) 90점은 A입니다.
단, 90~100 : A, 80~89 : B, 70~79 : C, 60~69 : D, 나머지 F
document.write()는 한번만 실행.
var score = prompt("점수를 입력하세요.");
if(score < 60){
result = "F";
}
else if(score < 70){
result = "D";
}
else if(score < 80){
result = "C";
}
else if(score < 90){
result = "B";
}
else{
result = "A";
}
document.write(score + "점은 " + result + "입니다.");
*/
/* 2
문제)짝홀수 맞추기 게임
숫자를 입력받고 계산하기 버튼 클릭 후 해당하는 함수에서 처리하는 순서
1. 입력값을 number1변수에 대입
document.폼네임.해당이름.value (예 : var tmp = document.fff.num1.value;)
2. 숫자가 입력되지 않았을 때 처리 (2번까지만 실행하고 해당 함수는 처리 끝.)
alert으로 "값을 입력하세요."
실행 후 커서를 해당 위치로 가게 함.(document.폼네임.해당이름.focus())
3. 숫자가 입력되었는지 확인
숫자입력 확인은 isNaN(입력변수) true면 숫자가 아님.
숫자가 아니면 alert으로 "숫자만 입력 가능합니다. 다시 입력하세요."
실행 후 커서를 해당 위치로 가게 하고 처리 끝
4. 여기 실행 조건은 값이 입력되었고, 입력값이 숫자인 경우 실행.
입력 값을 숫자로 변경한 후 짝/홀수 체크해서 alert으로 "짝수입니다."또는 "홀수입니다."라고 출력.
단, 서버 프로그램은 1211.html 로 하고, 서버 전송 방식은 get으로 함.
*/
function cal(){
var number1 = document.form1.num1.value; //name으로 조회
var number1 = document.getElementById("num1").value;
if(number1==""){ //if(document.form1.num1.value=="")
alert("값을 입력하세요");
document.form1.num1.focus();
return;
}
if(isNaN(number1)){
alert("숫자만 입력 가능합니다. 다시 입력하세요." );
document.form1.num1.value = "";
document.form1.num1.focus();
return;
}
number1 = parseInt(number1);
if(number1%2 == 0){
alert("짝수입니다.");
}
else{
alert("홀수입니다.");
}
if(confirm("서버로 보내시겠습니까?")){
//확인버튼 선택시 처리
document.form1.submit();
}
}
</script>
<h1>짝홀수 맞추기 게임</h1>
값을 입력하세요.
<form action="1211.html" name="form1" method="get">
숫자 : <input type="text" id="num1" name="num1" size="5" />
<input type="button" name="result" onclick="cal()" value="계산하기" />
</form>
</body>
</html>
** 1211_3 (로그인 성공/실패) **
* 실행은 1211_3실행
** 1211_4 (자바스크립트_학점매기기게임) **
<!DOCTYPEhtml>
<html>
<head>
<metacharset="UTF-8">
<title>자바스크립트-학점매기기 게임</title>
<script>
/*
문제)채점 버튼 클릭 시 체크 사항
1. 점수를 입력했는지 체크, 안되어 있을 경우 "점수를 입력하세요." 띄워주고 커서를 점수란으로 보내기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
/*body{
width:500;
margin:10px auto;
}*/
#middle{overflow:hidden;}
#left{
float:left;width:150px;background-color:orange;
}
#right{
float:right;width:350;background:brown;
}
#top{
width:150;background:green;
}
#bottom{
background:violet;
}
h1, p {width:300px;}
.ell{
white-space:nowrap;
overflow:hidden;
text-overflow:ellipsis;
}
</style>
</head>
<body>
<div id="top">"각 분야 전문가보다 해박"…구글, 멀티모달 AI 모델 '제미나이' 발표</div>
<div id="middle">구글은 제미나이는 구글 딥마인드와 구글 리서치 등 구글 조직 전반에 걸친 대규모 협업의 결과"라며 "구글 역사상 가장 큰 과학적 및 기술적 노력 중 하나"라고 소개했다.
<div id="left"> 1.0은 규모에 맞게 세 종류로 최적화했다. ▲방대하고 복잡한 작업에 적합한 가장 유용하고 규모가 큰 모델 '제미나이 울트라(Gemini Ultra)' ▲다양한 작업에서 확장하기에 가장 적합한 모델 '제미나이 프로(Gemini Pro)' ▲ 온디바이스(on-device) 작업에 가장 효율적인 모델 '제미나이 나노(Gemini Nano)'다.
</div>
<div id="right"> 따르면 특히 제미나이 울트라의 성능은 대형언어모델(LLM) 연구개발 평가에서 주로 사용되는 32개의 벤치마크 중 30개에서 기존의 최신 기술을 뛰어넘는 결과를 보여준 것으로 전해졌다.
</div>
</div>
<div id="bottom"> 물리학, 역사, 법률, 의학, 윤리 등 총 57개의 주제를 복합적으로 활용해 세계 지식과 문제 해결 능력을 평가하는 MMLU(대규모 멀티태스크 언어 이해) 테스트에서 90.04%의 점수를 기록한 제미나이 울트라는 전문가 인력보다 높은 결과를 기록한 최초의 모델이라는 설명이다.또한 제미나이 울트라는 고도의 추론 능력이 요구되는 다양한 영역에 걸친 멀티모달 작업으로 구성된 새로운 MMMU 벤치마크에서 59.4%의 최상위 점수를 획득했다.
</div>
<!--
<h1 class="ell">"각 분야 전문가보다 해박"…구글, 멀티모달 AI 모델 '제미나이' 발표
구글은 제미나이는 구글 딥마인드와 구글 리서치 등 구글 조직 전반에 걸친 대규모 협업의 결과"라며 "구글 역사상 가장 큰 과학적 및 기술적 노력 중 하나"라고 소개했다.
</h1>
<p class="ell"> 규모에 맞게 세 종류로 최적화했다. ▲방대하고 복잡한 작업에 적합한 가장 유용하고 규모가 큰 모델 '제미나이 울트라(Gemini Ultra)'
▲다양한 작업에서 확장하기에 가장 적합한 모델 '제미나이 프로(Gemini Pro)' ▲ 온디바이스(on-device) 작업에 가장 효율적인 모델 '제미나이 나노(Gemini Nano)'다.
따르면 특히 제미나이 울트라의 성능은 대형언어모델(LLM) 연구개발 평가에서 주로 사용되는 32개의 벤치마크 중 30개에서
기존의 최신 기술을 뛰어넘는 결과를 보여준 것으로 전해졌다.
물리학, 역사, 법률, 의학, 윤리 등 총 57개의 주제를 복합적으로 활용해 세계 지식과 문제 해결 능력을 평가하는 MMLU(대규모 멀티태스크 언어 이해) 테스트에서
90.04%의 점수를 기록한 제미나이 울트라는 전문가 인력보다 높은 결과를 기록한 최초의 모델이라는 설명이다.
또한 제미나이 울트라는 고도의 추론 능력이 요구되는 다양한 영역에 걸친 멀티모달 작업으로 구성된 새로운 MMMU 벤치마크에서 59.4%의 최상위 점수를 획득했다.
</p>
-->
</body>
</html>
** 예제 1207_8 **
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>html5 책갈피 기능</title>
</head>
<body>
<header>
<center>
<h2>< 책갈피 기능 ></h2>
</center>
</header>
<section>
<article>
<p>
<a href="#user">[이름]</a>
<a href="#addr">[주소]</a>
<a href="#tel">[전화번호]</a>
<a href="#foot">[참고]</a>
</p>
</article>
</section>
<p>"각 분야 전문가보다 해박"…구글, 멀티모달 AI 모델 '제미나이' 발표
구글은 제미나이는 구글 딥마인드와 구글 리서치 등 구글 조직 전반에 걸친 대규모 협업의 결과"라며 "구글 역사상 가장 큰 과학적 및 기술적 노력 중 하나"라고 소개했다.
</p>
<p>"각 분야 전문가보다 해박"…구글, 멀티모달 AI 모델 '제미나이' 발표
구글은 제미나이는 구글 딥마인드와 구글 리서치 등 구글 조직 전반에 걸친 대규모 협업의 결과"라며 "구글 역사상 가장 큰 과학적 및 기술적 노력 중 하나"라고 소개했다.
</p>
<p>"각 분야 전문가보다 해박"…구글, 멀티모달 AI 모델 '제미나이' 발표
구글은 제미나이는 구글 딥마인드와 구글 리서치 등 구글 조직 전반에 걸친 대규모 협업의 결과"라며 "구글 역사상 가장 큰 과학적 및 기술적 노력 중 하나"라고 소개했다.
</p>
<p><a name="user">홍길동</a></p>
<a href="#top">[TOP]</a>
<p>"각 분야 전문가보다 해박"…구글, 멀티모달 AI 모델 '제미나이' 발표
구글은 제미나이는 구글 딥마인드와 구글 리서치 등 구글 조직 전반에 걸친 대규모 협업의 결과"라며 "구글 역사상 가장 큰 과학적 및 기술적 노력 중 하나"라고 소개했다.
</p>
<p>"각 분야 전문가보다 해박"…구글, 멀티모달 AI 모델 '제미나이' 발표
구글은 제미나이는 구글 딥마인드와 구글 리서치 등 구글 조직 전반에 걸친 대규모 협업의 결과"라며 "구글 역사상 가장 큰 과학적 및 기술적 노력 중 하나"라고 소개했다.
</p>
<p>"각 분야 전문가보다 해박"…구글, 멀티모달 AI 모델 '제미나이' 발표
구글은 제미나이는 구글 딥마인드와 구글 리서치 등 구글 조직 전반에 걸친 대규모 협업의 결과"라며 "구글 역사상 가장 큰 과학적 및 기술적 노력 중 하나"라고 소개했다.
</p>
<P><a id="addr" name="addr">서울 마포구 월드컵</a></P>
<a href="#top">[TOP]</a>
<p>"각 분야 전문가보다 해박"…구글, 멀티모달 AI 모델 '제미나이' 발표
구글은 제미나이는 구글 딥마인드와 구글 리서치 등 구글 조직 전반에 걸친 대규모 협업의 결과"라며 "구글 역사상 가장 큰 과학적 및 기술적 노력 중 하나"라고 소개했다.
</p>
<p>"각 분야 전문가보다 해박"…구글, 멀티모달 AI 모델 '제미나이' 발표
구글은 제미나이는 구글 딥마인드와 구글 리서치 등 구글 조직 전반에 걸친 대규모 협업의 결과"라며 "구글 역사상 가장 큰 과학적 및 기술적 노력 중 하나"라고 소개했다.
</p>
<p>"각 분야 전문가보다 해박"…구글, 멀티모달 AI 모델 '제미나이' 발표
구글은 제미나이는 구글 딥마인드와 구글 리서치 등 구글 조직 전반에 걸친 대규모 협업의 결과"라며 "구글 역사상 가장 큰 과학적 및 기술적 노력 중 하나"라고 소개했다.
</p>
<p><a id="tel">02-123-4567</a></p>
<a href="#top">[TOP]</a>
<p>"각 분야 전문가보다 해박"…구글, 멀티모달 AI 모델 '제미나이' 발표
구글은 제미나이는 구글 딥마인드와 구글 리서치 등 구글 조직 전반에 걸친 대규모 협업의 결과"라며 "구글 역사상 가장 큰 과학적 및 기술적 노력 중 하나"라고 소개했다.
</p>
<p>"각 분야 전문가보다 해박"…구글, 멀티모달 AI 모델 '제미나이' 발표
구글은 제미나이는 구글 딥마인드와 구글 리서치 등 구글 조직 전반에 걸친 대규모 협업의 결과"라며 "구글 역사상 가장 큰 과학적 및 기술적 노력 중 하나"라고 소개했다.
</p>
<p>"각 분야 전문가보다 해박"…구글, 멀티모달 AI 모델 '제미나이' 발표
구글은 제미나이는 구글 딥마인드와 구글 리서치 등 구글 조직 전반에 걸친 대규모 협업의 결과"라며 "구글 역사상 가장 큰 과학적 및 기술적 노력 중 하나"라고 소개했다.
</p>
<p id="foot">기타</p>
<a href="#top">[TOP]</a>
<p>"각 분야 전문가보다 해박"…구글, 멀티모달 AI 모델 '제미나이' 발표
구글은 제미나이는 구글 딥마인드와 구글 리서치 등 구글 조직 전반에 걸친 대규모 협업의 결과"라며 "구글 역사상 가장 큰 과학적 및 기술적 노력 중 하나"라고 소개했다.
</p>
<p>"각 분야 전문가보다 해박"…구글, 멀티모달 AI 모델 '제미나이' 발표
구글은 제미나이는 구글 딥마인드와 구글 리서치 등 구글 조직 전반에 걸친 대규모 협업의 결과"라며 "구글 역사상 가장 큰 과학적 및 기술적 노력 중 하나"라고 소개했다.
</p>
<p>"각 분야 전문가보다 해박"…구글, 멀티모달 AI 모델 '제미나이' 발표
구글은 제미나이는 구글 딥마인드와 구글 리서치 등 구글 조직 전반에 걸친 대규모 협업의 결과"라며 "구글 역사상 가장 큰 과학적 및 기술적 노력 중 하나"라고 소개했다.
</p>
</body>
</html>
태그 모양을 다양하게 변경할 수 있음. text, radio, checkbox (0개 이상 선택가능) , password, button, hidden, submit, reset 등이 있음 cf) radio, checkbox 은 name이 같은것끼리 그룹으로 묶인다.(name은 되도록 중복되지 않게 사용한다.) <input type="checkbox" name="computer" value="cpu" />cpu 값은 value값이 넘어간다(프론트에서 서버에요청할때 맨뒤 변수 cpu에 해당하는 값) / 화면에 출력되는것은 맨 뒤의 cpu
name
해당 type의 이름을 지정
readonly
태그를 읽기전용으로 지정 예) <input readonly>
maxlength
해당 태그 최대 글자 수를 지정
required
해당 태그가 필수태그로 지정됨. 필수 태그를 입력하지 않고 submit버튼을 누르면 에러메시지가 브라우저에서 출력됨(HTML5추가)
특징 - List 인터페이스르르 구현하기 떄문에 데이터의 저장순서가 유지되고 중복을 허용함
Object 배열을 애용해서 데이터를 순차적으로 저장
배열에 순서대로 저장되며, 배열에 더 이상 저장할 공간이 없으면 보다 큰 새로운 배열을 생성해서 기존의 배열 내용을 새로운 배열로 복사한 다음에 저장
* ArrayList의 생성자와 메서드
메소드
설명
ArrayList()
크기가 10인 ArrayList생성
boolean add(Object o)
ArrayList의 마지막에 객체 추가 , 성공 true
void add (int index, Object element)
지정된 위치에 객체 저장
boolean contains(Object o)
지정된 객체가 ArrayList에 포함되어 있는지 확인
Object get(int index)
지정된위치에 저장된 객체 반환
Object remove(int index)
지정된 위치에 있는 객체 제거
boolean retainAll(Collection c)
ArrayList에 저장된 객체 중에서 주어진 컬렉션과 공통된 것들만을 남기고 나머지는 삭제
ArrayList 크기(길이)가 10인 ArrayList가 생겨도 값이 5개만 들어오면 크기가 5로 바뀜.
** 예제 etc pakage MySample1201_3 (ArrayList) **
package exec;
import java.util.ArrayList;
import java.util.Collections;
public class MySample1201_3 {
public static void main(String[] args) {
// ArrayList
ArrayList<String> list1 = new ArrayList<String>(10);
list1.add("A");
list1.add("B");
list1.add("C");
list1.add("D");
System.out.print("list1 초기 상태 : ");
System.out.println(list1 + " - size : " + list1.size());
System.out.println("\n인덱스1에 B 추가");
list1.add(1, "B");
System.out.print("B추가 후 : ");
System.out.println(list1 + " - size : " + list1.size());
System.out.println("\n인덱스2의 값 삭제");
list1.remove(2);
System.out.print("인덱스2삭제 후 : ");
System.out.println(list1 + " - size : " + list1.size());
System.out.println("\n인덱스 2번째 위치 값 불러오기 : " + list1.get(2));
System.out.println();
ArrayList list2 = new ArrayList(10); //타입<String>쓰지않으면, ArrayList에 객체를 넣을 수 있다.
list2.add(new Integer(5)); //5를 넣지안고 Integer객체에 5를 넣은 이유
list2.add(new Integer(4));
list2.add(new Integer(2));
list2.add(new Integer(0));
list2.add(new Integer(1));
list2.add(new Integer(3));
System.out.println("list2 : " + list2);
ArrayList list3 = new ArrayList(list2.subList(1, 4)); //인덱스 1번째부터 (4-1) 위치까지 가져오는 것
System.out.println("list3 : " + list3);
print(list2, list3);
Collections.sort(list2); //<T> : 어떠한 데이터탑입도 다 받는다는 의미
Collections.sort(list3);
print(list2, list3);
//list2에 list3 전체가 포함되어 있는지 확인(true.false)
System.out.println("list2.containsAll(list3) - " + list2.containsAll(list3));
System.out.println("list3.containsAll(list2) - " + list3.containsAll(list2));
}
static void print(ArrayList list1, ArrayList list2) {
System.out.println("list1 : " + list1);
System.out.println("list2 : " + list2);
System.out.println();
}
}
** 문제 etc pakage MySample1201_4 (ArrayList) **
// ArrayList /* * 문제)5명의 사람이름을 입력받아서 ArrayList에 저장한 후에 '김'씨 성을 가진 사람을 모두 출력하는 프로그램. * 입력예)홍길동 * 이둘리 * 김길동 * 김둘리 * 최길동 * 출력예)[김길동] [김둘리] * 김씨 성을 가진 분은 모두 2명입니다. * 단, 입력시 nextLine() 사용하며, '김'으로 시작한 것을 찾는 메서드는 get(i) 가져와서 startsWith("김")->true, false */
package exec;
import java.util.ArrayList;
import java.util.Scanner;
public class MySample1201_4 {
public static void main(String[] args) {
// ArrayList
/*
* 문제)5명의 사람이름을 입력받아서 ArrayList에 저장한 후에 '김'씨 성을 가진 사람을 모두 출력하는 프로그램.
* 입력예)홍길동
* 이둘리
* 김길동
* 김둘리
* 최길동
* 출력예)[김길동] [김둘리]
* 김씨 성을 가진 분은 모두 2명입니다.
* 단, 입력시 nextLine() 사용하며, '김'으로 시작한 것을 찾는 메서드는 get(i) 가져와서 startsWith("김")->true, false
*/
ArrayList<String> name = new ArrayList<String>(5);
int cnt = 0; //몇명인지 체크
int i;
Scanner scn = new Scanner(System.in);
System.out.println("5명의 이름을 입력해 주세요.");
for(i = 0 ; i < 5 ; i++ ) {
name.add(scn.nextLine());
}
String str;
for(i = 0 ; i < name.size() ; i++) {
str = name.get(i); //str쓰지않고 name.get(i)를 직접 사용가능
if(str.startsWith("김")) {
cnt++;
System.out.print("[" + name.get(i) + "] ");
}
}
System.out.println();
System.out.println("김씨 성을 가진 분은 모두 " + cnt + "입니다.");
}
}
** 문제 etc pakage MySample1201_5 (ArrayList) **
package exec;
import java.util.ArrayList;
import java.util.Scanner;
public class MySample1201_5 {
public static void main(String[] args) {
// ArrayList 문제
/*
* 문제)5명의 별명을 입력받아 ArrayList에 저장하고 이들 중 별명의 길이가 제일 긴 별명을 출력하는 프로그램
* 입력예)세일러문
* 크루지
* 놀부
* 순대렐라
* 달려라하니
* 출력예)가장 길이가 긴 별명은 > 달려라하니
* 단, 별명의 길이는 모두 다르게 입력함.
*/
Scanner scn = new Scanner(System.in);
ArrayList<String> nick = new ArrayList<String>(5);
int i, maxnickIndex = 0;
int tmp = 0;
System.out.println("5명의 이름을 입력하세요.");
for(i = 0 ; i < 5 ; i++) {
nick.add(scn.nextLine());
if(nick.get(i).length() > tmp) {
tmp = nick.get(i).length();
maxnickIndex = i;
}
// for(i = 0 ; i < nick.size() ; i++) {
// if(nick.get(i).length() > tmp) {
// tmp = nick.get(i).length();
// maxnickIndex = i;
// }
}
System.out.println("가장 길이가 긴 별명은 > " + nick.get(maxnickIndex));
// //선생님 풀이
// ArrayList<String> list = new ArrayList<String>();
// int[] lengthArr = new int[5];
// int max = lengthArr[0];
// int i;
//
// for(i = 0 ; i < 5 ; i++) {
// list.add(scn.nextLine());
// }
//
// for(i = 0 ; i < 5 ; i++) {
// lengthArr[i] = list.get(i).length();
//
// if(max < lengthArr[i]) {
// max = lengthArr[i];
// }
// }
//
// for(i = 0 ; i < 5 ; i++) {
// if(max == list.get(i).length()) {
// System.out.println("가장 길이가 긴 별명은 > " + list.get(i));
// break;
// }
// }
}
}
** 문제 etc pakage MySample1201_6 (ArrayList) **
package etc;
public class Student {
private int grade;
private int ban;
private int num;
private String name;
private int korean;
private int english;
private int math;
private int totalScore;
private double avg;
private int ranking;
public Student() {
this(0,0,0,"",0,0,0);
}
public Student(int grade, int ban, int num, String name, int korean, int english, int math) {
setGrade(grade);
setBan(ban);
setNum(num);
setName(name);
setKorean(korean);
setEnglish(english);
setMath(math);
setTotalScore(getKorean() + getEnglish() + getMath());
setAvg((double)getTotalScore() / 3);
setRanking(0);
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public int getBan() {
return ban;
}
public void setBan(int ban) {
this.ban = ban;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getKorean() {
return korean;
}
public void setKorean(int korean) {
this.korean = korean;
}
public int getEnglish() {
return english;
}
public void setEnglish(int english) {
this.english = english;
}
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
public int getTotalScore() {
return totalScore;
}
public void setTotalScore(int totalScore) {
this.totalScore = totalScore;
}
public double getAvg() {
return avg;
}
public void setAvg(double avg) {
this.avg = avg;
}
public int getRanking() {
return ranking;
}
public void setRanking(int ranking) {
this.ranking = ranking;
}
public String toString() {
String value = "등수 : " + getRanking() + "\n";
value += getGrade( ) + "학년" + getBan() + "반 " +
getNum() + "번 " + getName() + "\n";
value += "국어 : " + getKorean() + ", 영어 : " + getEnglish() + ", 수학 : " + getMath() + "\n";
value += "총점 : " + getTotalScore() + "\n";
value += "평균 : " + String.format("%.1f", getAvg()) + "\n";
return value;
}
}
package etc;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class MySample1201_6 {
public static int randomRange(int min, int max, Random random) {
if(min > max) {
return min;
}
//난수발생 - min부터 max값 사이 난수 발생
return random.nextInt((max+1)-min)+min;
}
public static void main(String[] args) {
Random random = new Random();
//학생 리스트 작성
List<Student> list = new ArrayList<Student>();
//랜덤 점수 입력
int i;
for(i = 1 ; i <= 20 ; i++) {
list.add(new Student(1,1,1, "홍길동"+i,
randomRange(40, 100, random),
randomRange(40, 100, random),
randomRange(40, 100, random)));
}
//등수 산정 전 출력
System.out.println("###########################");
System.out.println("등수 산정 전 출력");
System.out.println("###########################");
for(i = 0 ; i < list.size() ; i++) {
Student student = list.get(i);
System.out.println(student);
}
//등수를 적용하기 위해 내림차순 정렬
int j;
Student tmp;
for(i = 0 ; i < (list.size()-1) ; i++) {
for(j = i+1 ; j < list.size() ; j++) {
if(list.get(i).getTotalScore() < list.get(j).getTotalScore()) {
tmp = list.get(i);
list.set(i, list.get(j));
list.set(j, tmp);
}
}
}
System.out.println();
//등수 산정한 후 출력
System.out.println("###########################");
System.out.println("등수 산정 후 출력");
System.out.println("###########################");
int ranking = 0; //등수
int order = 0; //동일 등수 증가 값
Student student;
//등수 산정 및 출력
for( i = 0 ; i < list.size() ; i++) {
student = list.get(i);
if(i == 0) {
//등수 포기 값으로 1로 설정
ranking++;
//동일 등수 증가 값도 1로 설정
order++;
}
else {
//총점이 같다면
if(list.get(i-1).getTotalScore() == student.getTotalScore()) {
//동일 등수시 증가값만 적용(등수 ranking 바로 앞과 동일)
order++;
}
else {
//총점이 틀리면(이전 등수에 동일 등수 증가 값을 더함)
ranking += order;
//동일 등수 증가 값 초기화
order = 1;
}
}
//등수 부여
student.setRanking(ranking);
//출력
System.out.println(student);
}
}
}
package exec;
import java.util.Scanner;
public class MySample1130_2 {
static Scanner scn = new Scanner(System.in);
static void ticketing(int age) throws AgeException{ //ticketing 호출하는 쪽에서 예외처리 해야한다.
if(age < 20) {
//AgeException e = new AgeException("나이 입력 오류");
//throw e;
//위 두줄을 한줄로
throw new AgeException("나이 입력 오류");
}
}
public static void main(String[] args) {
// 예외처리 - 사용자 예외처리 (=클래스 예외처리)
/*
* 문제)20살 미만이 입력될 경우 계속해서 입력을 받고 20살 이상이 입력되면 "티켓발행 성공"이라고 출력하고 프로그램 종료
*/
System.out.print("나이를 입력하세요.>");
int age =scn.nextInt();
try {
ticketing(age);
}
catch(AgeException e) {
e.printStackTrace();
}
System.out.println("main() 메소드 끝.");
}
}
class AgeException extends Exception{ //Exception 상속 받아야함 (안받으면 Object상속받음)
AgeException(){
this("나이 입력 오류");
}
AgeException(String msg){
super(msg);
}
}
//문제)20살 미만이 입력될 경우 계속해서 입력을 받고 20살 이상이 입력되면 "티켓발행 성공"이라고 출력하고 프로그램 종료
//문제)20살 미만이 입력될 경우 계속해서 입력을 받고 20살 이상이 입력되면 "티켓발행 성공"이라고 출력하고 프로그램 종료
package exec;
import java.util.Scanner;
public class MySample1130_2 {
static Scanner scn = new Scanner(System.in);
static void ticketing(int age) throws AgeException{ //ticketing 호출하는 쪽에서 예외처리 해야한다.
if(age < 20) {
//AgeException e = new AgeException("나이 입력 오류");
//throw e;
//위 두줄을 한줄로
throw new AgeException("나이 입력 오류");
}
}
public static void main(String[] args) throws InterruptedException { //Thread.sleep(1000); 사용하기위해 throws 해준다.
// 예외처리 - 사용자 예외처리 (=클래스 예외처리)
/*
* 문제)20살 미만이 입력될 경우 계속해서 입력을 받고 20살 이상이 입력되면 "티켓발행 성공"이라고 출력하고 프로그램 종료
*/
while(true) {
System.out.print("나이를 입력하세요.>");
int age = scn.nextInt();
try {
ticketing(age);
System.out.println("티켓 발행 성공");
break;
}
catch(AgeException e) {
e.printStackTrace();
//예쁘게 보이기위해 Thread.sleep(1000); 와 throws InterruptedException 사용해줌
//위 e.printStackTrace(); 대신 아래문자열로 사용 가능
System.out.println(e.getMessage());
}
Thread.sleep(1000); //1초 대기
System.out.println();
}
}
}
class AgeException extends Exception{ //Exception 상속 받아야함 (안받으면 Object상속받음)
AgeException(){
this("나이 입력 오류");
}
AgeException(String msg){
super(msg);
}
}
** 예제 MySample1130_3 (예외처리)**
package exec;
//예외처리가 어디서 일어나는지 알아보기 위해 쓰인다.(흔하게 쓰이진 않음)
public class MySample1130_3 {
public static void main(String[] args) {
// 예외처리 (연결된 예외처리)
try {
install();
}
catch(InstallException e) {
System.out.println("1111111111111111111111111");
e.printStackTrace();
}
catch(Exception e) {
System.out.println("2222222222222222222222222");
e.printStackTrace();
}
finally {
System.out.println("*************************");
}
}
static void install() throws InstallException{
try {
startInstall();
copyFiles();
}
catch(SpaceException e) {
InstallException ie = new InstallException("설치중 예외발생11");
//InstallException의 원인 예외를 SpaceException으로 지정
ie.initCause(e); //지정된 예외를 예외로 등록
throw ie;
//
}
catch(MemoryException e) {
InstallException ie = new InstallException("설치중 예외발생22");
ie.initCause(e);
throw ie;
}
finally {
deleteTempFiles();
}
}
static void startInstall() throws SpaceException, MemoryException{
if(!enoughSpace()) {
throw new SpaceException("설치 공간이 부족함.");
}
if(!enoughMemory()) {
throw new MemoryException("메모리가 부족함");
}
}
static void copyFiles() {
System.out.println("설치에 필요한 파일들을 복사.");
}
static boolean enoughSpace() {
System.out.println("설치시 필요한 공간이 충분한지 확인.");
return false;
}
static boolean enoughMemory() {
System.out.println("설치시 필요한 메모리 확인");
return true;
}
static void deleteTempFiles() {
System.out.println("설치 후 설치시 사용한 임시파일 삭제.");
}
}
class InstallException extends Exception{
InstallException(String msg){
super(msg);
}
** Java.lang패키지 **
- 가장 기본이 되는 클래스들을 포함하고 있으며, import문 없이도 사용가능
Object클래스 : 모든 클래스의 최고 조상
Object 클래스의 메소드
설명
public Boolean equals(Object obj)
객체 자신과 객체 obj가 같은 객체인 기 (같으면 true)
public Class getClass()
객체 자신의 클래스 정보를 담고 있는 Class 인스턴스를 반환
public int hachCode()
객체 자신의 해시코드를 반화
public String toString()
객체 자신의 정보를 문자열로 반환
Object클래스에 equals메소드는 참조변수가 같은 객체를 참조하는 판다.
String 클래스의 epuals메소드는 주소값이 아닌 내용을 비교하도록 오버라이딩 되어있음.
- 목적 : 예외 발생시 실행중인 프로그램의 갑작스런 비정상 종료를 막고, 비정상 종료를 막아 정상적인 실행 상태를 유지할 수 있도록 하는 것
- 구조
try{
예외처리하길 원하는 실행코드;
}
// catch는 여러개 사용가능함
catch(Exception1 e1){
Exception1이 발생했을 경우, 처리하기위한 문장
}
catch(Exception2 e2){
Exception2이 발생했을 경우, 처리하기위한 문장
}
....
finally{
예외발생 여부와 상관없이 무조건 실행될 코드
}
프로그램이 실행 중 어떤 원인의 의해서 오작동을 하거나 비정상적으로 종료되는 경우를 프로그램 에러 또는 오류하고 함.
프로그램이 실행되는 도중 발생하는 예외를 처리하기 위해
try / catch / finally 문을 사용
컴파일 에러
- 컴파일 시에 발생하는 에러
런타임 에러
- 실행 시에 발생하는 에러
논리적 에러
- 실행은 되지만, 의도와 다르게 동작하는 것
* 자바에서 실행 시 발생할 수 있는 프로그램 오류
- 에러(error) : 프로그램 코드에 의한 수습될 수 없는 심각한 오류
- 예외(exception) : 프로그램 코드에 의해서 수습될 수 있는 오류
예외가 발생하더라도 프로그래머가 이에대한 적절한 코드를 미리 작성해 놓아 프로그램이 비정상적으로 종료되는 것을 막는 것을 의미함.
- 예외 클래스 계층구조 : 모든 예외의 최고 조상은 Exception클래스
FileNotFoundException
ClassNotFoundException
DataFormatException
ArrayIndexOutOfBoundsException
** 예제 exec Pakage _ MySample1129 (예외처리) **
package exec;
public class MySample1129 {
public static void main(String[] args) {
// 예외처리
int[] a = {2, 0};
int b = 4;
//int c =a[2]; //먼저 실행 후 오류 확인
try {
int c = b / a[2]; //int c = a[2];
System.out.println("c " + c);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("배열 인덱스 오류 발생");
}
// catch(ArithmeticException e) {
// System.out.println("0으로 나눌수 없습니다. : " + e);
// }
//프로그램은 위에서 아래로 흐르기에 가장 최고조상인 Exception 은 가장 아래에 있어야 오류 안난다.
catch(Exception e) {
System.out.println("뭔지몰라 오류 발생 : " + e);
}
finally {
System.out.println("무조건 실행됨");
}
System.out.println("try~catch 끝.");
}
}
** 예제 MySample1129 _ 2 (예외처리) **
package exec;
public class MySample1129_2 {
public static void main(String[] args) {
// 예외처리
//0으로 나누었을 떄 "0으로 나눌 수 없습니다." 메세지 출력 후 계속 진행
int number = 10;
int result = 0;
int i;
// try {
// for(i = 0 ; i < 10 ; i++) {
// result = number/(int)(Math.random( )* 10);
// System.out.println("result " + result);
// }
// }
// catch(ArithmeticException e) {
// System.out.println("0으로 나눌 수 없습니다.: " + e);
// }
//
//
// for(i = 0 ; i < 10 ; i++) {
// try {
// result = number/(int)(Math.random( )* 10); //0~9
// System.out.println("result " + result);
// }
// catch(ArithmeticException e) {
// System.out.println("0으로 나눌 수 없습니다.: " + e);
// }
//
// }
//실행순서
System.out.println("1");
try {
System.out.println("2");
int a = 5 / 0;
System.out.println("3");
}
catch(Exception e){
System.out.println("4");
}
finally {
System.out.println("4-2");
}
System.out.println("5");
}
}
** 예제 MySample 1129_7 (클래스 예외처리 - 예외클래스 생성 후 다른클래스 메소드에서 예외처리) **
package exec;
import java.util.Scanner;
public class MySample1129_7 {
static Scanner scn = new Scanner(System.in); //main메소드가 static이라서
public static int inputScore() throws ScoreException{ //예외 클래스 만든것을 메소드에서 예외처리함
int score = scn.nextInt();
if(score < 0 || score > 100){
ScoreException ex = new ScoreException("점수는 0~100점 사이 입력하세요.");
throw ex;
}
return score;
}
public static void main(String[] args) {
// 예외처리(클래스)
try {
System.out.print("국어 점수 입력>");
int kor = inputScore();
System.out.println("국어 점수는 " + kor + "점 입니다.");
System.out.print("영어 점수 입력>");
int eng = inputScore();
System.out.println("영어 점수는 " + eng + "점 입니다.");
}
catch(ScoreException ex) {
System.out.println("오류메세지 : " + ex.getMessage());
}
finally {
System.out.println("프로그램 종료합니다.");
}
}
}
class ScoreException extends Exception{ //예외처리클래스
ScoreException(){
super("점수 입력 오류");
}
ScoreException(String nsg){
super(nsg);
}
}
** 문제 MySample1129_8 (예외처리) **
// 예외처리 - 문제 /* * 20번 반복해서 랜덤발생을 0~9까지 발생시킨후 랜덤값으로 나눈 결과를 화면에 출력하되 0으로 나누면 오류 발생함. * ArithmeticException 에 대한 예외처리를 적용하고 예외에 대한 출력은 0으로 처리하고, 0으로 나눈 횟수 발생한 * 건수를 최종 출력하는 프로그램 * 출력예) * 16 * 20 * 11 * 0 -> 랜덤발생이 0으로 되어 예외처리부분. * 33 * 100 * ... * 0 발생 건수 : 1건 * 단, number = 100; 으로 초기 설정 후 (int)(Math.random() * 10); 처리함 */
package exec;
public class MySample1129_8 {
public static void main(String[] args) {
// 예외처리 - 문제
/*
* 20번 반복해서 랜덤발생을 0~9까지 발생시킨후 랜덤값으로 나눈 결과를 화면에 출력하되 0으로 나누면 오류 발생함.
* ArithmeticException 에 대한 예외처리를 적용하고 예외에 대한 출력은 0으로 처리하고, 0으로 나눈 횟수 발생한
* 건수를 최종 출력하는 프로그램
* 출력예)
* 16
* 20
* 11
* 0 -> 랜덤발생이 0으로 되어 예외처리부분.
* 33
* 100
* ...
* 0 발생 건수 : 1건
* 단, number = 100; 으로 초기 설정 후 (int)(Math.random() * 10); 처리함
*/
int number = 100;
int result, cnt = 0;
int i;
// for (i = 0 ; i < 20 ; i++) {
// try {
// result = number / (int)(Math.random() * 10);
// System.out.println(result);
// }
// catch(ArithmeticException a) {
// result = 0;
// cnt++;
// System.out.println(result);
// }
// }
// System.out.println("0 발생 건수 : " + cnt);
// //다른방법 (깔끔함)
// for (i = 0 ; i < 20 ; i++) {
// try {
// result = number / (int)(Math.random() * 10);
// }
// catch(ArithmeticException a) {
// result = 0;
// cnt++;
// }
// finally {
// System.out.println(result);
// }
// }
// System.out.println("0 발생 건수 : " + cnt);
//결과는 위화 동일하며 try~catch문을 사용하지 않고 프로그램 구현.
for (i = 0 ; i < 20 ; i++) {
int tmp = (int)(Math.random() * 10);
if(tmp != 0) {
result = number / tmp;
}
else {
result = 0;
cnt++;
}
System.out.println(result);
}
System.out.println("0 발생 건수 : " + cnt);
}
}
다른 클래스를 작성할 때 기본이 되는 틀을 제공하면서, 다른 클래스 사이의 중간 매개 역할 까지 담당하는 추상 클래스를 의미함
추상 클래스 - 추상메소드, 생성자, 필드, 일반 메소드로 포함
인터페이스 - 오로지 추상 메소드( public abstract )와 상수( public static final )만을 포함
인터페이스클래스에 있는 메소드는 모두 추상메소드 → abstract 를 쓰지않아도 컴파일러자 자동으로 추상메소드로 읽어준다.
문법) 인터페이스이름 = 클래스이름
문법)
접근제어자 interface 인터페이스이름{
public static final 타입 상수이름 = 값; ... public abstract 리턴타입 메소드이름(매개변수목록); ... }
//인터페이스를 상속 받을 때 문법 class 클래스이름 implements 인터페이스이름 {...}
//인터페이스이름자리에 , 로 여러개의 인터페이스클래스 명 올 수 있다.
모든 필드는 public static final 모든 메소드는 public abstract 제어자( public static final , public abstract )는 생략 가능하며 생략된 제어자는 컴파일시 자동 추가
** 예제 1128 **
package inter;
interface Animal{
public static final int A = 10; //public static final 생략 가능
public abstract void cry(); //public abstract 생략 가능
}
class Cat implements Animal{
public void cry() {
System.out.println("야옹야옹..");
}
}
class Dog implements Animal{
public void cry() {
System.out.println("멍멍..");
}
}
public class MySample1128 {
public static void main(String[] args) {
// 인터페이스
Cat c = new Cat();
Dog d = new Dog();
c.cry();
d.cry();
}
}
** 예제 1128_2 **
package inter;
interface Providable{
public abstract void leisureSports(); //레저스포즈
public abstract void sightSeeling(); //관광
public abstract void food(); //음식
}
class KoreaTour implements Providable{
public void leisureSports() {
System.out.println("한강에서 수상스키 투어");
}
public void sightSeeling() {
System.out.println("경복궁 관광 투어");
}
public void food() {
System.out.println("불고기");
}
}
class TourGuide{
private Providable tour = new KoreaTour();
public void leisureSports() {
tour.leisureSports();
}
public void sightSeeling() {
tour.sightSeeling();
}
public void food() {
tour.food();
}
}
public class MySample1128_2 {
public static void main(String[] args) {
// 인터페이스 (캡슐, 상속, 다형성)
TourGuide guide = new TourGuide();
guide.leisureSports();
guide.sightSeeling();
guide.food();
}
}
** 문제 1125_3 **
package inter;
/*
문제) 인터페이스 Animal2 와 Pet을 정의하며, Animal2 클래스는 울음소리(cry)를 Pet클래스는 움직임(play)를 정의함.
고양이2 클래스와 강아지2 클래스에서 울음소리와 움직임에 대한 재정의를 구현함.
단, 고양이는 울음소리는 "야오야용" 움직임은 "폴짝폴짝 뛰어다니기"로 출력하고
강아지는 울음소리는 "멍멍" 움식임은 "산책하기"로 출력함.
*/
interface Animal2{
public abstract String cry();
}
interface Pet{
public abstract void play();
}
class Cat2 implements Animal2, Pet{
public String cry() {
return "야옹야옹";
}
public void play() {
System.out.println("폴짝폴짝");
}
}
class Dog2 implements Animal2{
public String cry() {
return "몽몽";
}
public void play() {
System.out.println("산책하기");
}
}
public class MySample1128_3 {
public static void main(String[] args) {
// 인터페이스를 통한 다중상속 (implements A, B)
Dog2 d = new Dog2();
Cat2 c = new Cat2();
System.out.println(c.cry());
c.play();
System.out.println();
System.out.println(d.cry());
d.play();
}
}
** 예제 1128_4 **
package inter;
interface Gamer{
public static final int GAME_MAX_LEVEL = 100;
public abstract void doGame();
}
interface Singer{
int AUDITION_MAX_CHANCE = 10; //public static final 이 생략됨
int GAME_MAX_LEVEL = 99; //public static final 이 생략됨
void singSong(); //public abstract 생략됨
}
class Student implements Gamer, Singer{
String name;
int score;
Student(String name, int score){
this.name = name;
this.score = score;
}
public void doGame() {
System.out.println(name + "은 게임을 합니다.");
}
public void singSong() { //메소드 오버라이딩하려면 접근지정자까지 일치해야해서 생략된 public써줘야한다.
System.out.println(name + "은 노래를 부릅니다.");
}
}
public class MySample1128_4 {
public static void main(String[] args) {
// 인터페이스 다중상속
Student s = new Student("김둘리", 83);
System.out.println("게임의 최고 레벨(Gamer) : " + Gamer.GAME_MAX_LEVEL);
System.out.println("가수의 최고 레벨(Singer) : " + Singer.GAME_MAX_LEVEL);
s.doGame();
System.out.println(s.name + "의 점수 : " + s.score);
System.out.println("오디션 최대 기회 : " + Singer.AUDITION_MAX_CHANCE);
}
}
** 문제 inter2 pakage (RemoteControl) **
package inter2;
public interface RemoteControl {
public static final int MAX_VOLUME = 10;
public static final int MIN_VOLUME = 0;
void turnOn();
public abstract void turnOff();
public abstract void setVolume(int volume);
}
/*
turnOn 은 "TV를 켭니다." 또는 "오디오를 켭니다." / turnOff는 "TV를 끕니다." 또는 "오디오를 끕니다."
setVolume은 max값과 min값에 대한 체크 후 tv는 "현재 TV볼륨은 : 5", 오디오는 "현재 오디오볼륨은 : 7"
출력예)1111111111
TV를 켭니다.
현재 TV볼륨 : 5
2222222222
오디오를 켭니다.
현재 오디오볼륨 : 5
오디오를 켭니다.
현재 오디오볼륨 : 5
3333333333
오디오를 겹니다.
현재 오디오 볼륨 : 5
4444444444
TV를 켭니다.
현재 TV볼륨은 : 5
*/
package inter2;
public class Tv implements RemoteControl{
private int volume;
public void turnOn() {
System.out.println("TV를 켭니다.");
}
public void turnOff() {
System.out.println("TV를 끕니다.");
}
public void setVolume(int volume) {
if (volume > MAX_VOLUME) {
this.volume = MAX_VOLUME;
}
else if(volume < MIN_VOLUME) {
this.volume = MIN_VOLUME;
}
else {
this.volume = volume;
}
System.out.println("현재 TV볼륨은 : " + getVolume());
}
public int getVolume() {
return this.volume;
}
}
package inter2;
public class Audio implements RemoteControl{
private int volume; //인스터스변수의 접근자가 private이면 보통 set/get메소드 사용한다.
public void turnOn() {
System.out.println("오디오를 켭니다.");
}
public void turnOff() {
System.out.println("오디오를 끕니다.");
}
public void setVolume(int volume) {
if (volume > MAX_VOLUME) {
this.volume = MAX_VOLUME;
}
else if (volume < MIN_VOLUME) {
this.volume = MIN_VOLUME;
}
else {
this.volume = volume;
}
System.out.println("현재 TV볼륨은 : " + getVolume());
}
public int getVolume() {
return this.volume;
}
}
package inter2;
public class MyClassMain {
public static void main(String[] args) {
// 인터페이스
/*출력예)1111111111
TV를 켭니다.
현재 TV볼륨 : 5
2222222222
오디오를 켭니다.
현재 오디오볼륨 : 5
오디오를 켭니다.
현재 오디오볼륨 : 5
3333333333
오디오를 겹니다.
현재 오디오 볼륨 : 5
4444444444
TV를 켭니다.
현재 TV볼륨은 : 5
*/
System.out.println("1111111111");
MyClass myClass1 = new MyClass();
myClass1.rc.turnOn();
myClass1.rc.setVolume(5);
System.out.println("2222222222"); //MyClass에서 생성자를 통해
Audio a = new Audio();
MyClass myClass2 = new MyClass(a); //new MyClass(new Audio()); 사용해도된다 (후에 a 사용없을시)
System.out.println("3333333333"); //MyClass의 매개변수 없는 메소드를 통해
MyClass myClass3 = new MyClass();
myClass3.methodA();
System.out.println("4444444444"); //MyClass의 매개변수 있는 메소드를 통해
MyClass myClass4 = new MyClass();
myClass4.methodA(new Tv());
}
}
** 예제 inter3 pakage (그래픽카드) **
package inter3;
public interface GraphicsCard {
//제조사
public abstract String company();
//모델
public String model();
//메모리
public int memory();
//출력
public void write(PointColor pointcolor);
}
package inter3;
public class Rgb {
private int red;
private int green;
private int blue;
public Rgb() {
this(0,0,0);
}
public Rgb(int red, int green, int blue) {
this.red = red;
this.green = green;
this.blue = blue;
}
public int getRed() {
return this.red;
}
public void setRed(int red) {
this.red = red;
}
public int getGreen() {
return this.green;
}
public void setGreen(int green) {
this.green = green;
}
public int getBlue() {
return this.blue;
}
public void setBlue(int blue) {
this.blue = blue;
}
}
package inter3;
public class PointColor {
//x좌표값
private int x;
//y좌표값
private int y;
//RGB색상표
private Rgb rgb;
public PointColor() {
this(0,0,new Rgb());
}
public PointColor(int x, int y, Rgb rgb) {
this.x = x;
this.y = y;
this.rgb = rgb;
}
public Rgb getRgb() {
return this.rgb;
}
public void setRgb(Rgb rgb) {
this.rgb = rgb;
}
public int getX() {
return this.x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return this.y;
}
public void setY(int y) {
this.y = y;
}
}
package inter3;
public class NvidiaGeForce implements GraphicsCard{
private String company;
private String model;
private int memory;
NvidiaGeForce(String model, int memory){
company = "NVIDIA";
this.model = model;
this.memory = memory;
}
//제조사
public String company() {
return this.company;
}
//모델
public String model() {
return this.model;
}
//메모리
public int memory() {
return this.memory;
}
//출력
public void write(PointColor pointColor) {
if(pointColor != null) {
Rgb rgb = pointColor.getRgb();
System.out.println("---" + company + "GraphicsCard 출력");
System.out.println("1.좌표를 구한다.");
System.out.println("x : " + pointColor.getX());
System.out.println("y : " + pointColor.getY());
System.out.println("2.color 구성.");
// if(rgb != null) {
// System.out.println("Rgb : " + rgb.getRed());
// System.out.println("Green : " + rgb.getGreen());
// System.out.println("Blue : " + rgb.getBlue());
// }
//바로 위 주석을 아래와 같이 변경 가능.
if(pointColor.getRgb() != null) {
System.out.println("Rgb : " + pointColor.getRgb().getRed());
System.out.println("Green : " + pointColor.getRgb().getGreen());
System.out.println("Blue : " + pointColor.getRgb().getBlue());
}
System.out.println("3.모니터 좌표에 색상출력.");
}
}
}
package inter3;
public class AmdRadeon implements GraphicsCard{
private String company;
private String model;
private int memory;
public AmdRadeon(String model, int memory) {
this.company = "AMD";
this.model = model;
this.memory = memory;
}
//제조사
public String company() {
return this.company;
}
//모델
public String model() {
return this.model;
}
//메모리
public int memory() {
return this.memory;
}
//출력
public void write(PointColor pointColor) {
if(pointColor != null) {
Rgb rgb = pointColor.getRgb();
System.out.println("---" + company + "GraphicsCard 출력");
System.out.println("1.color를 구성한다.");
if(rgb != null) {
System.out.println("Blue : " + rgb.getBlue()); //pointColor.getRgb().getBlue()
System.out.println("Red : " + rgb.getRed()); //pointColor.getRgb().getBlue()
System.out.println("Green : " + rgb.getBlue()); //pointColor.getRgb().getBlue()
}
System.out.println("2.좌표를 구한다.");
System.out.println("x : " + pointColor.getX());
System.out.println("y : " + pointColor.getY());
System.out.println("3.여기서 모니터 좌표에 색상 출력");
}
}
//제너레이트 사용법 : Source -> Generate Getters and Setters -> selectAll
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getMemory() {
return memory;
}
public void setMemory(int memory) {
this.memory = memory;
}
}
package inter3;
public class GraphicsCardMain {
//.java 에있는 인스턴스변수(private)는 set/get메서드로 접근한다.
//운영체제에서 그래픽 출력
public void operatingSystemWrite(GraphicsCard graphicsCard, PointColor pointColor) {
if (graphicsCard != null) {
System.out.println("그래픽 카드 출력");
System.out.println("회사명 : " + graphicsCard.company());
System.out.println("모델명 : " + graphicsCard.model());
System.out.println("메모리 : " + graphicsCard.memory());
graphicsCard.write(pointColor);
}
}
public static void main(String[] args) {
//인터페이스 예제
//라데온 그래픽 카드 생성
GraphicsCard amdRadeon = new AmdRadeon("Rx 5000", 4096);
//엔비디아 그래픽 카드 생성
NvidiaGeForce nvidiaGeForce = new NvidiaGeForce("Gefpre GT 710", 2048);
//포인트 컬러 생성
PointColor pointColor = new PointColor();
pointColor.setX(100);
pointColor.setY(200);
pointColor.setRgb(new Rgb(255,128,100));
// PointColor pointColor = new PointColor(100,200,new Rgb(255,128,100));
GraphicsCardMain gCardMain = new GraphicsCardMain();
gCardMain.operatingSystemWrite(amdRadeon, pointColor);
System.out.println();
gCardMain.operatingSystemWrite(nvidiaGeForce, pointColor);
}
}
class Parent4{
int x = 100;
void method() {
System.out.println("Parent4 method()...");
}
}
class Child4 extends Parent4{
int x = 200;
void method() {
System.out.println("x = " + x);
System.out.println("super.x = " + super.x);
System.out.println("this.x = " + this.x);
}
}
public class MySample1123 {
public static void main(String[] args) {
// 다형선 - 참조형변수와 인스턴스 연결
// 다형성 _ 부모타입의 참조변수로 자식의 객체를 만든다.
Parent4 p = new Child4();
Child4 c = new Child4();
System.out.println("p.x = "+ p.x); //인스턴스 변수는 참조(잠조형변수=부모의 인스턴스변수)하는 값이 찍힌다. p.x = 200
p.method();
System.out.println("c.x = " + c.x);
c.method();
//Parent p = new Child();
//인스턴스 변수
//부모에게 있고 자식에도 있으면 -> 부모꺼 실행
//부모에게 있고 자식에게 없으면 -> 부모꺼 실행
//부모에는 없고 자식에게 있으면 -> 오류2
//메소드
//부모에게 있고 자식에도 있으면 -> 자식꺼 실행 (메소드 오버라이딩)
//부모에게 있고 자식에게 없으면 -> 부모꺼 실행
//부모에는 없고 자식에게 있으면 -> 오류2
}
}
** 예제 1123_2 (다형성) **
class Product2{
int price; //제품가격
int bonusPoint; //제품구매시 제공 보너스 점수
Product2(int price){
this.price = price;
bonusPoint = (int)(price / 10.0); //제품가격의 10퍼센트 적용
}
}
class Tv3 extends Product2{
Tv3(){
super(900);
}
public String toString() {
return "Tv";
}
}
class Computer2 extends Product2{
Computer2(){
super(500);
}
public String toString() {
return "Computer";
}
}
class Buyer{
int money = 10000; //보유금액
int bonusPoint = 0; //보유보너스
void buy(Product2 p) { //매개변수의 다형성
if (money < p.price) { //보유금액보다 사려는 가격비 비싼경우 못사게 처리
System.out.println("잔액 부족으로 물건을 살 수 없습니다.");
return; //프로그램 끝
}
money -= p.price; //this.money = this.money - p.price;
bonusPoint += p.bonusPoint; //this.bonusPoint = this.bonusPoint + p.bonusPoint
System.out.println(p + "을(를) 구매하셨습니다.");
}
}
public class MySample1123_2 {
public static void main(String[] args) {
// 다형성 - 매개변수의 다형성
Buyer b = new Buyer();
System.out.println("현재 보유중인 현금은 " + b.money + "만원 입니다.");
Product2 p = new Tv3(); //Tv3 p = new Tv3(); 으로 해도 결과는 같음 (Buyer 클래스 buy메서드에 매개변수가 매개변수가 다형성)
b.buy(p); //b.buy(new Tv3()); -> main()메서드에서 구매제품에 대한 정보를 알 수 없음.
System.out.println("현재 구매한 가격은 " + p.price + "입니다.");
System.out.println("현재 남은 돈은 " + b.money + "만원 입니다.");
System.out.println("현재 보유중인 보너스 점수는 " + b.bonusPoint + "점 입니다.");
System.out.println("\n");
Product2 p2 = new Computer2();
b.buy(p2);
System.out.println("현재 구매한 가격은 " + p2.price + "입니다.");
System.out.println("현재 남은 돈은 " + b.money + "만원 입니다.");
System.out.println("현재 보유중인 보너스 점수는 " + b.bonusPoint + "점 입니다.");
}
}
** 예제 1123_3 (다형성 - 객체를 배열로) **
class Product3{
int price;
int bonusPoint;
Product3(int price){
this.price = price;
this.bonusPoint = (int)(price*0.1);
}
}
class Tv4 extends Product3{
Tv4(){
super(100);
}
public String toString() {
return "Tv";
}
}
class Computer3 extends Product3{
Computer3(){
super(300);
}
public String toString() {
return "컴퓨터";
}
}
class Audio extends Product3{
Audio(){
super(50);
}
public String toString() {
return "오디오";
}
}
class Buyer2{
int money = 1000;
int bonusPoint = 0;
Product3[] item = new Product3[10];
int cnt = 0; //배열에 사용될 카운트
void buy(Product3 p) {
if(money < p.price) {
System.out.println("잔액 부족으로 물건을 살 수 없습니다.");
return;
}
money -= p.price;
bonusPoint += p.bonusPoint;
item[cnt++] = p; //p - 객체의 시작 주소값
System.out.println(p + "을(를) 구매하셨습니다."); //각 클래스에 toString 오버라이딩 메서드 호출
int i;
for(i = 0 ; i < item.length ; i++) {
System.out.println("item[" + i + "] : " + item[i]);
}
}
void summary() {
int sum = 0; //구입물품 가격 합계
String itemList = ""; //구입물품 목록
int i;
//구입한 물품 총 가격과 목록
for(i = 0 ; i < item.length ; i++) {
if(item[i] == null)
break;
sum += item[i].price;
itemList += item[i].toString() + ", ";
}
System.out.println("구입하신 물품의 총 금액은 " + sum + "만원 입니다.");
System.out.println("구입하신 제품은 "+ itemList + "입니다.");
System.out.println("구입하신 제품의 총 보너스 점수는 " + bonusPoint + "점 입니다.");
}
}
public class MySample1123_3 {
public static void main(String[] args) {
// 다형성 - 객체를 배열로
Buyer2 b = new Buyer2();
b.buy(new Tv4());
b.buy(new Computer3());
b.buy(new Audio());
b.summary();
}
}
** Vector 클래스 **
- 자바의 배열은 고정 길이를 사용함. 즉, 배열이 한번 생성되면 배열의 길이를 증가하거나 감소 할 수 없다는 단점이 있음. (배열복사 말고)
- Vector클래스는 가변길이의 배열이라고 할 수 있음. (내부적으로 배열복사)
- 즉 Vector클래스는 객체에 대한 참조값을 저장하는 배열이므로 다양한 객체들이 하나의 Vectoer에 저장될 수 있고 길이도 필요에 따라 증감할 수 있다는 점이 배열과 다른 점이다.
.Vector 클래스의 생성자
Vector 클래스의 생성자
설 명
Vector()
10개의 데이터를 저장할 수 있는 길이의 객체를 생성한다. 저장공간이 부족한 경우 10개씩 증가한다.
Vector(int size)
size 개의 데이터를 저장할 수 있는 길이의 객체를 생성한다. 저장공간이 부족할 경우 size개씩 증가한다.
Vector(int size, int incr)
size 개의 데이터를 저장할 수 있는 길이의 객체를 생성한다. 저장공간이 부족한 경우 incr개씩 증가한다.
. Vetor 클래스의 주요 메서드
메서드 / 생성자
설 명
Vector()
10개의 객체를 저장할 수 있는 Vector인스턴스를 생성한다. 10개이상의 인스턴스가 저장되면, 자동적으로 크기가 증가된다.
Vector가 비어있는지 검사한다. 비어있으면 결과값으로 true, 비어있지 않으면 false를 반환한다.
boolean get(int index)
저장된 위지(index)의 객체를 반환한다. 반환타입이 Object타입이므로 적절한 타입으로의 형변환이 필요하다.
int size()
Vetor에 저장된 객체의 개수를 반환한다.
** 예제 1123_4 **
import java.util.Vector;
class Buyer3{
int money = 1000;
int bonusPoint = 0;
Vector item = new Vector();
void buy(Product3 p) {
System.out.println("vector size() : " + item.size());
if(money < p.price) {
System.out.println("잔액이 부족하여 물건을 살 수 없습니다.");
return;
}
money -= p.price;
bonusPoint += p.bonusPoint;
item.add(p);
System.out.println(p + "을(를) 구매하셨습니다.");
}
void summary() {
int sum = 0;
String itemList = "";
int i;
Product3 p = null;
if(item.isEmpty() == true) { //if(item.size()==0)
System.out.println("구입한 물건이 없습니다.");
return;
}
for(i = 0 ; i < item.size() ; i++) {
// p = (Product3)item.get(i); //p == item.get(i) ???
sum += p.price;
itemList += (i == 0) ? p : ("," + p) ; //p + ", ";
}
System.out.println("구입한 총 금액 " + sum + "만원 입니다.");
System.out.println("구입한 물품은 " + itemList + "입니다.");
}
//환불
void refund(Product3 p) {
if(item.remove(p)) {
money += p.price;
bonusPoint -= p.bonusPoint;
System.out.println(p + "을(를) 반풍하셨습니다.");
}
else {
System.out.println("해당제품이 없습니다.");
}
}
}
public class MySample1123_4 {
public static void main(String[] args) {
// Vector() 클래스
Buyer3 b = new Buyer3();
Tv4 t = new Tv4();
Computer3 com = new Computer3();
Audio audio = new Audio();
b.buy(t);
b.buy(com);
b.buy(audio);
b.summary();
System.out.println("\n");
//환불
b.refund(com);
b.summary();
b.refund(com); //이미 삭제된 상품이므로 vector에 없음. 오류발생
}
}
** 추상클래스 (abstract class) **
- 하나 이상의 추상 메소드를 포함하는 클래스를 의미함
- 추상메소드 : 자식클래스에서 반드시 오버라이딩 해야만 사용할 수 있는 메소드
- 반드시 사용되어야 하는 메소드를 추상클레스에 추상메소드로 선언을 하면, 이 클래스를 상속받는 모든 클래스에서 이 추상 메소드를 반드시 재정의 해야함
abstract class 클래스 이름 {
...
abstract 반환타입 메소드이름();
...
}
- 추상클래스는 추상메소드를 포함하고 있다는 점 이외에는 일반 클래스와 모든점이 같다. 즉 생성자와 변수, 일반 메소드도 포함 할 수 있음.
** 예제 abs패키지 _ 1123_5 **
package abs;
abstract class Animal{
int num;
void numChk() {
System.out.println("num : " + num);
}
abstract void cry(); //추상클래스에는 추상메서드가 있어야한다.
}
class Cat extends Animal{
void cry() { //추상클래스에 있는 추상메소드 오버라이딩 한 것. but 상속받는 클래스에서 오버라이딩 할 때는 abstarct 쓰지 않는다.
System.out.println("야오야옹");
}
}
class Dog extends Animal{
void cry() {
System.out.println("멍멍....");
}
}
public class MySample11223_5 {
public static void main(String[] args) {
// 추상클래스
//Animal a = new Animal(); //추상클래스는 인스턴스를 생성할 수 없음.(객체생성 불가)
Cat c = new Cat(); //Animal c = new Cat(); 가능
Dog d = new Dog(); //Animal d = new Dog(); 가능
c.cry();
d.cry();
}
}
** 예제 abs패키지 _ 1123_6 (포켓몬) **
package abs;
abstract class Pokemon
{
private String name;
// Pokemon(){
//
// }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
abstract void attack(); //공격
abstract void sound(); //소리
}
class Pikachu extends Pokemon{
Pikachu(){
super.setName("피카츄");
}
void attack() {
System.out.println("전기공격");
}
void sound() {
System.out.println("피카피카");
}
}
class Spuirtle extends Pokemon{
Spuirtle(){
setName("꼬부기");
}
void attack() {
System.out.println("물뿌리기 공격");
}
void sound() {
System.out.println("꼬북꼬북");
}
}
public class MySample1123_6 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//추상클래스
Pikachu p1 = new Pikachu();
System.out.println("포켓몬 이름은 " + p1.getName());
p1.attack();
p1.sound();
Spuirtle s1 = new Spuirtle();
System.out.println("포켓몬 이름은 " + s1.getName());
s1.attack();
s1.sound();
}
}
** abs2 패키지 _ 추상클래스 상속 _ Animal 클래스 / Bird 클래스 / Cat 클래스 / Dog 클래스 **
package abs2;
public abstract class Animal {
//동물이름
protected String name; //private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
//어떻게 우는지
public abstract String getCry();
//어떻게 움직이는지
public abstract String getMove();
//무엇을 먹는지
public abstract String getFood();
//출력
public abstract void print();
}
package abs2;
public class AnimalMain {
public static void main(String[] args) {
// 추상클래스 메인
Dog dog = new Dog("재롱이");
Cat cat = new Cat("나비");
Bird bird = new Bird("짹짹이");
cat.print();
System.out.println();
dog.print();
System.out.println();
bird.print();
System.out.println();
cat.setCry("어흥");
cat.print();
System.out.println();
bird.setMove("펄럭펄럭");
bird.print();
System.out.println();
dog.setFood("건조 닭고기");
dog.print();
}
}
** 실습 abs1 패키지 **
/* *추상클래스 *문제)Animal클래스를 추상클래스로 정의하고 이름(name), 나이(age) 변수를 정의하고 생성자(매개변수2개)를 통해 값 저장 * 이동하는 메서드(move)로 먹는 메서드(eat)로 정의하여 이동은 "이동한다", 먹는것은 "먹는다"로 출력함. * 자식 클래스(Dog, Cat)에서 반드시 재정의 하도록 bark() 메서드로 짖는걸 구현함. *출력예)이동한다. * 멍멍 * 먹는다. * * 이동한다. * 야옹 * 먹는다. */
class Today{ //extends Object 생략
private String weather;
public String getWeather() {
return this.weather;
}
public void setWeather(String weather) {
this.weather = weather;
}
void greeting() {
System.out.println("즐거운 하루 되세요.");
}
// //자식클래스 생성자에 super(weather); 사용할 경우
// Today(String weather){
// setWeather(weather);
// }
}
class Morning extends Today{
Morning(String weather){
//super(); //생략되어있다.
setWeather(weather); //super. 생략됨 (Morning 클래스에 setWeather 메서드가 없기때문)
// //super(weather);
}
void greeting() {
System.out.println("좋은 아침입니다. 오전에는 " + super.getWeather() + "입니다.");
//super. 생략가능 (Morning 클래스에 setWeather 메서드가 없기때문)
}
}
class Lunch extends Today{
Lunch(String weather){
setWeather(weather);
}
void greeting() {
System.out.println("즐거운 점심 입니다. 점심에는 " + getWeather() + "입니다.");
}
}
class Dinner extends Today{
Dinner(String weather){
super.setWeather(weather);
}
void greeting() {
System.out.println("행복한 오후되세요. 오후에는 " + getWeather() + "가 내리겠습니다.");
}
}
public class MySample1122 {
public static void main(String[] args) {
//상속 + 오버라이딩
Morning m = new Morning("맑음");
Lunch l = new Lunch("흐림");
Dinner d = new Dinner("비");
m.greeting();
l.greeting();
d.greeting();
}
}
** 실습 1122_2 (오버라이딩 + 접근제어자) **
class Car3{
private int door;
private String gearType;
private String color;
Car3(String color){
//setColor(color);
//setGearType("auto");
//setDoor(4);
this(color, "auto", 4); //this. 같은 클래스 내에있는 타입갯수와 종류에 맞는 생성자 불러옴
}
Car3(String color, String gearType){
//setColor(color);
//setGearType(gearType);
//setDoor(4);
this(color, gearType, 4);
}
Car3(String color, String gearType, int door){
setColor(color);
setGearType(gearType);
setDoor(door);
}
public int getDoor() {
return this.door;
}
public void setDoor(int door) {
this.door = door;
}
public String getGearType() {
return this.gearType;
}
public void setGearType(String gearType) {
this.gearType = gearType;
}
public String getColor() {
return this.color;
}
public void setColor(String color) {
this.color = color;
}
}
class SportsCar extends Car3{
int speedLimit; //제한속도
SportsCar(String color){
super(color);
//setColor(color); //super(); 생략되어있어서 오류남
this.speedLimit = 200;
}
SportsCar(String color, int speedLimit){
super(color);
this.speedLimit = speedLimit;
}
SportsCar(String color, String gearType){
super(color, gearType);
this.speedLimit = 200;
}
SportsCar(String color, String gearType, int speedLimit){
super(color, gearType);
this.speedLimit = speedLimit;
}
SportsCar(String color, String gearType, int door, int speedLimit){
super(color, gearType, door);
this.speedLimit = speedLimit;
}
public String toString() {
return "차량의 색은 "+ getColor() +"이고, " + getGearType() + "이며, 문의 개수는 " + getDoor() + "개이며," + " 제한 속도는 " + speedLimit + " 입니다.";
}
}
public class MySample1122_2 {
public static void main(String[] args) {
/*
실행결과)차량의 색은 red이고, auto이며, 문의 개수는 4개이며,
제한 속도는 330 입니다.
(단, 차량 색은 반드시 입력받고, 제한속도가 없을 경우 200, 기어타입이 없을 경우 auto로 정의함)
문 개수가 없을 경우 기본 4개로 정의함.
클래스와 변수는 세팅되있는것만 사용한다.
단 정수가 하나만들어온 경우 speedLimit으로 여긴다.
*/
SportsCar cs = new SportsCar("red", 330);
System.out.println(cs.toString()); //.toString 생략되어있음
}
}
** 다형성(polymorphism) **
하나의 객체가 여러가지 타입을 가질 수 있는 것을 의미.
부모 클래스 타입의 참조 변수로 자식클래스 타입의 인스턴스를 참조 할 수 있도록 구현.
참조 변수의 다형성
class Parent{...}
class Chlid extends Parent{...}
...
Parent pa = new Parent(); // 허용
chlid ch = new Child(); // 허용
Parent pc = new Chlid(); // 허용
Child cp = new Parent(); // 오류 발생
//상속을 통해 확장된 수 있으나 축소될수는 없음. 자식클래스에서 사용할 수 있는 멤버(인스턴스변수, 인스턴스 메소드...)의 개수가 언제나 부모 클래스와 같거나 많게됨
instanceof : 연산자 / 참조변수가 참조하고 있는 인스턴스 실제 타입 확인
문법)참조변수 instanceof 클래스이름 -> true, false 리턴
다형성에서 어떠한 변수와 메소드를 사용할 것인가?
* 인스턴스 변수 // 부모에게 있고 자식에도 있으면 -> 부모꺼 실행 // 부모에게 있고 자식에게 없으면 -> 부모꺼 실행 // 부모에는 없고 자식에게 있으면 -> 오류2
* 메소드 // 부모에게 있고 자식에도 있으면 -> 자식꺼 실행 (메소드 오버라이딩) // 부모에게 있고 자식에게 없으면 -> 부모꺼 실행 // 부모에는 없고 자식에게 있으면 -> 오류2
** 1122_3 예제 (다형성) **
class A{
void methodA() {
System.out.println("methodA()...");
}
}
class B extends A{
void methodB() {
System.out.println("methodB()...");
}
}
public class MySample1122_3 {
public static void main(String[] args) {
A obj = new B();
obj.methodA(); //가능
// obj.methodB(); //불가능
B obj2 = new B();
obj.methodA(); //가능
obj2.methodB(); //가능
}
}
** 예제 1122_4 (다형성) **
class Car4{
String color;
int door;
void drive() {
System.out.println("drive()...Car4");
}
void stop() {
System.out.println("stop()...Car4");
}
}
class FireEngine extends Car4{
void water() {
System.out.println("water()...FireEngine");
}
}
public class MySample1122_4 {
public static void main(String[] args) {
// 다형성
// Car4 c = null;
// FireEngine f = new FireEngine();
// FireEngine f2 = null;
//
// f.water();
// c = f; //다형성 => Car4 c = new FireEngine(); 과 같다.
// //내부적으로 형변환이 발생했음.(up-casting)
//
// //c.water(); //불가능(부모형 참조변수로 자식객체를 바라볼수 있으나 자식객체에 메서드는 사용할 수 없음)
//
// f2 = (FireEngine)c; //안되지만 (FireEngine)으로 강제 형변환해서 사용가능
// //down-casting이므로 강제 형변환 꼭해야함.
// f2.water();
//불가능한예제
Car4 c = new Car4(); //= new FireEngine();로 변경하면 1.싫애시에도오류안남
// Car4 c = new FireEngine();
Car4 c2 = null;
FireEngine f = null;
Car4 c3 = new FireEngine();
c.drive();
//f = (FireEngine)c; //f = c; 는 불가능 하나 형변환을 통해서 가능
//컴파일은 가능하나 시행시 오류 발생
f.drive(); // 실행시오류
c2 = f; //up-casting
//c2.water(); //불가능 : c2 참조변수는 클래스 타입이 Sard4이고 water()a메서드는
c2.drive();
c2.stop(); // FireEngine클래스의 메서드이기 떄문에 호출불가
}
}
** 예제 1122_6 (다형성) **
class Animal3{
void breath() {
System.out.println("숨쉬기");
}
public String toString() {
return "몰라";
}
}
class Lion3 extends Animal3{
public String toString() {
return "사자";
}
}
class Rabbit extends Animal3{
public String toString() {
return "토끼";
}
}
class Monkey extends Animal3{
public String toString() {
return "원숭이";
}
public void printA() {
System.out.println("printA()...");
}
}
class ZooKeeper{
// void feed(Lion3 lion) {
// System.out.println(lion + "에게 먹이주기...");
// }
//
// void feed(Rabbit rabbit) {
// System.out.println(rabbit + "에게 먹이주기...");
// }
//
// void feed(Monkey monkey) {
// System.out.println(monkey + "에게 먹이주기...");
// }
void feed(Animal3 animal) {
System.out.println(animal + "에게 먹이주기...");
}
}
public class MySample1122_5 {
public static void main(String[] args) {
// 다형성
ZooKeeper j = new ZooKeeper();
//
// Lion3 lion1 = new Lion3();
// j.feed(lion1);
//
// Rabbit rabbit = new Rabbit();
// j.feed(rabbit);
//
// Monkey monkey = new Monkey();
// j.feed(monkey);
Animal3 lion1 = new Lion3(); //객체생성은 Lion3, 바라보는관점은 Animal3 -> Animal3에 있는 것들을 사용할 수 있음
j.feed(lion1);
Animal3 rabbit = new Rabbit();
j.feed(rabbit);
Animal3 monkey = new Monkey();
j.feed(monkey);
j.feed(new Animal3()); // Animal3 animal = new Monkey(); //다시보기!!!!
monkey.printA(); // 오류 : monkey참조변수는 Animal3클래스의 참조변수이므로
// Monkey() 클래스에 있는 printA()메서드 접근 불가능
}
}
** 예제 1122_6 (다형성_ 연산자 instanceof) **
class Parent3{
}
class Child3 extends Parent3{
}
class Brother extends Parent3{
}
public class MySample1122_6 {
public static void main(String[] args) {
// 다형성 (instanceof 연산자)
Parent3 p = new Parent3();
System.out.println(p instanceof Object); // true
System.out.println(p instanceof Parent3); // true
System.out.println(p instanceof Child3); // false
Parent3 p2 = new Child3();
System.out.println(p2 instanceof Object); // true
System.out.println(p2 instanceof Parent3); // true
System.out.println(p2 instanceof Child3); // true
//부모에게 있고 자식에도 있으면 -> 자식꺼 실행
//부모에게 있고 자식에게 없으면 -> 부모꺼 실행
//부모에는 없고 자식에게 있으면 -> 오류
}
}
/* 1 문제)친구정보를 기록할 MyFriendInfo 클래스를 상세정보를 기록할 MyFriendDetailInfo클레스에 상속하고 이름, 나이는 MyFriendInfo 클래스에서 주소와 전화번호는 MyFriendDetailInfo 클래스에서 입력할 수 있도록 구성함. 출력예)이름 : 이순신 나이 : 100 주소 : 성균관 전화 : 010-1111-2222 단, 각 클래스에서 출력하는 메서드가 존재하며, main 메서드에서는 생성자와 출력메서드 한번만 호출(자식클래스)하여 적용함.(메인에는 두줄) 입력값은 생성자를통해서 하드코딩하여 저장함. new 클래스( "이순신", 100, "성균관 ', "010-1111-2222") */
class MyFriendInfo{
String name;
int age;
MyFriendInfo(String name, int age){
this.name = name;
this.age= age;
}
void printMyFriendInfo(){
System.out.println("이름 : " + name);
System.out.println("나이 : " + age);
}
}
class MyFriendDetailInfo extends MyFriendInfo{
String add;
String num;
MyFriendDetailInfo(String name, int age, String add, String num){
super(name, age);
// super.name = name; //이렇게 쓰지 않는 이유 : 나중에 배울 오버라이딩 배우면 앎
// super.age = age; //이렇게 쓰려면 위의 MyFriendInfo 메서드 없어야 함.
this.add = add;
this.num = num;
}
void printMyFriendDetailInfo() {
super.printMyFriendInfo(); //여기서는 super. 생략되도 됨 (이유 : 같은 메소드명이 자식에 없기때문임)
System.out.println("주소 : " + add);
System.out.println("전화 : " + num);
}
}
public class MySample1121 {
public static void main(String[] args) {
//상속
MyFriendDetailInfo mfdi = new MyFriendDetailInfo("이순신", 100, "성균관 ", "010-1111-2222");
mfdi.printMyFriendDetailInfo();
}
}
class MyFriendInfo
{
MyFriendInof(){
}
}
class MyFriednDetailInfo extends MyFriendInfo
{
MyFriednDetailInfo(){
super();
}
}
//class MyFriendInfo 와 class MyFriednDetailInfo가 생성자 없이 만들어지면
//JVM이 매개변수없는 생성자를 하나씩 만들어준다. (코드에 보이지 않아도 존재한다)
//-> but 생성자를 만들어 놓으면 JVM이 매개변수없는 생성자를 생성해주지 않는다.
//상속 받는 자식클래스의 매개변수 없는 생성자에는 super();이 생략되어있다.
생성자 or 매서드 에서 변수의 순위
지역변수 -> 인스턴스변수 -> 부모변수
생성자 or 메서드에서 변수 쓰임
지역변수 : 변수명만 쓴다.
인스턴스변수 : this.변수명
부모변수 : super.변수명
// 모든 클래스는 object.class를 상속받게 되어있다.(object 는 상속받는 클래스의 최상위 클래스라고 생각하면 된다.)
// JDK가 object.class 를 상속받게 해둔다.
** 예제 1121_2 (상속) **
// 상속 /* 실행결과)kind : SPACE, number : 1 kind : HEART, number : 7 (실행시 마다 변경) */
import java.util.Random;
class Card2{
static final int KIND_MAX = 4; //카드무늬수 (클래스 상수로 정의)
static final int NUM_MAX =13; //무니별 카드수
static final int SPADE = 4;
static final int DIAMOND = 3;
static final int HEART = 2;
static final int CLOVER = 1;
int kind;
int number;
Card2(){
this(SPADE, 1);
}
Card2(int kind, int number){
this.kind = kind;
this.number = number;
}
public String toString() {
String[] kinds = {"", "CLOVER", "HEART", "DIAMOND", "SPADE"};
String numbers = "0123456789XJQK"; //숫자 10은 X로 사용
return "kind : " + kinds[this.kind] + ", number : " + numbers.charAt(this.number); //charAt this.number 의 위치값만 뽑아옴
}
}
class Deck{
final int CARD_NUM = 52; //카드개수
Card2[] cardArr = new Card2[CARD_NUM];
Deck() {
int i = 0, k, n;
for(k = Card2.KIND_MAX ; k > 0 ; k--) { //4
//KIND_MAX 4부터 시작(4~1)
for(n = 0 ; n < Card2.NUM_MAX ; n++) { //13
//NUM_MAX = 13 (1~12)
System.out.println("Deck()생성자 : i = " + i + ", k = " + k + ", n = " + n);
cardArr[i++] = new Card2(k, n+1);
}
}
}
//지정된 위치(index)에 있는 카드 하나를 꺼내 반환함.
Card2 pick(int index) { //리턴타입 Card 객체
return cardArr[index];
}
Card2 pick() { //메소드 오버로딩
int index = (int)Math.random() * 52; //0~51사이값, 오류뜨면 Math앞에 java.lang. 써준다.
return pick(index);
}
//카드 순서 섞기
void shuffle() {
int i, r;
Card2 tmp;
for(i = 0 ; i < cardArr.length ; i++) {
r = (int)(java.lang.Math.random() * CARD_NUM); //0~51사이
tmp = cardArr[i];
cardArr[i] = cardArr[r];
cardArr[r] = tmp;
}
}
void printArr() {
int i;
for(i = 0 ; i < cardArr.length ; i++)
{
System.out.println("cardArr[" + i + "] : " + cardArr[i]);
}
}
}
public class MySample1121_2 {
public static void main(String[] args) {
// 상속
/*
실행결과)kind : SPACE, number : 1
kind : HEART, number : 7 (실행시 마다 변경)
*/
Deck d = new Deck();
Card2 c = d.pick(0); //카드를 섞기 전에 제일 위 카드 뽑기
System.out.println("before : " + c.toString());
System.out.println("before : " + c); //윗줄과 결과 같다.
System.out.println("\n");
d.printArr();
d.shuffle(); //카드 섞기
c = d.pick(0); //카드 섞고나서 제일 위 카드 뽑기
System.out.println("after : " + c.toString());
System.out.println("\n");
d.printArr();
}
}
** 오버라이딩 (overriding) **
상속관계에서 부모 클래스로부터 상속받은 메서드의 내용(구현부)을 자식클래스에서 변경하는 것
자손 클래스에서 오버라이딩하는 메서드는 조상 클래스의 메서드와 선언부가 같아야한다.
-.이름(메소드명)이 같아야한다.
-.매개변수가 같아야 한다.
-.반환타입이 같아야한다.
** 예제 1121_3 (오버라이딩) **
class Point2{
int x;
int y;
String getLocation() {
return "x : " + x + "y : " + y;
}
}
class Point3D extends Point2{
int z;
String getLocation() {
//return "x : " + x + ", y : " + y + ", z : " +z;
//부모클래스의 getLocation()메서드 호출방법
return super.getLocation() +", z : " + z;
}
}
public class MySample1121_3 {
public static void main(String[] args) {
//오버라이딩
Point3D p3 = new Point3D();
p3.x = 10;
p3.y = 20;
p3.z = 30;
System.out.println(p3.getLocation());
}
}
** 예제 1121_4 (오버라이딩) **
class Parent{
int x = 10;
}
class Child extends Parent{
int x = 20;
void methodA() {
int x = 30;
System.out.println("x : " + x); //지역변수
System.out.println("this.x : " + this.x); //인스턴스 변수
System.out.println("super.x : " + super.x); //부모에 정의된 인스턴스 변수
}
}
public class MySample1121_4 {
public static void main(String[] args) {
Child c = new Child();
c.methodA();
}
}
** 예제1121_5 (오버라이딩) **
class Point3{
int x, y;
Point3(){
this(0,0);
}
Point3(int x, int y){
this.x = x;
this.y = y;
}
String getLocation() {
return "x : " + x + ", y : " + y;
}
}
class Point3D2 extends Point3{
int z;
Point3D2(){
this(0, 0, 0);
}
Point3D2(int x, int y, int z){
super(x, y);
//super.x = x;
//super.y = y;
this.z = z;
}
String getLocation() {
//return "x : " + x + ", y : " + y + ", z : " + z;
return super.getLocation();
}
}
public class MySample1121_5 {
public static void main(String[] args) {
//오버라이딩
Point3D2 p3 = new Point3D2(1, 2 , 3);
System.out.println(p3.getLocation());
//getLocation()메서드를 Point3클래스 메서드를 호출하는 방법 2가지
//첫번째
Point3 p = new Point3(1, 2);
System.out.println(p.getLocation());
//두번째
System.out.println(p3.getLocation()); //Point3D2의 getLocation()메서드를 return super.getLocation();로 바꾼다.
}
}
class Clothes{
void cutHeight() {
System.out.println("높이 수선하였습니다.");
}
void cutWidth() {
System.out.println("넓이를 수선하였습니다.");
}
void showPrice() {
System.out.println("수선비용은 : 5000원");
}
}
class Reform extends Clothes{
void cutHeight() {
System.out.println("높이를 다시 맞춰 수선하였습니다.");
}
void cutWidth() {
System.out.println("넚이를 다시 맞춰 수선하였습니다.");
}
}
public class MySample1121_5 {
public static void main(String[] args) {
//오버라이딩
Clothes ct = new Clothes();
Reform re = new Reform();
ct.cutHeight();
ct.cutWidth();
ct.showPrice();
re.cutHeight();
re.cutWidth();
re.showPrice(); //자식메소드를 통해 부모메소드를 불러옴
}
}
** 접근 제어자 (access modifier) **
- 멤버 또는 클래스에 사용되어 해당하는 멤버 또는 클래스 외부에서 접근하지 못하도록 제한하는 역할
* 접근제어자의 종류
접근제어자
사용 가능 범위
private
같은 클래스 내에서만 접근 가능 / 접근제어자 가장 강함
default
같은 패키지 내에서만 접근 가능 (아무것도 쓰지 않으면 default)
protected
같은 패키지 내에서와 다른 패키지의 자손클래스에서 접근 가능
public
접근 제한 없음 / 접근제어자 가장 약함
- 위로 갈 수 록 접근제어가 강해진다.
cf) 패키지란? + 패키지 생성
- src 아래 (default package) 가 package이다.
- src 클릭후 new -> package 생성 또는 src 클릭후 new -> class 생성 (생성할 때 package명에 사용할 package명 입력하고 생성)
* 대상에 따라 사용할 수 있는 접근 제어자
대상
사용가능한 접근 제어자
클래스
public, (default)
메서드 멤버변수
public, protected, (default), private
지역변수
없음(메서드 안에 있기에 메서드 끝나면 끝남)
* 접근제어자 사용 이유
- 외부로부터 데이터 보호
- 내부적으로 사용되는 부분을 감추기 위해
** 예제 1121_6 (접근제어자) **
class Time{
private int hour, minute, second;
Time(int hour, int minute, int second){
setHour(hour); //this.hour = hour;
setMinute(minute); //this.minute = minute;
setSecond(second); //this.second = second;
}
public void errorPrint(String msg) {
System.out.println("현재 오류는 " + msg + "입니다.");
}
public int getHour() {
return this.hour;
}
public void setHour(int hour) {
//시간 0 ~ 23시 사이 값만 허용
if(hour < 0 || hour >23) {
errorPrint("시간(0~23시 사이) 오류");
return; //이 아래로 실행하지 않고 중간에 나를 호출한 곳으로 다시 돌아가겠다는 의미
}
this.hour = hour;
}
public int getMinute() {
return this.minute;
}
public void setMinute(int minute) {
//분은 0~59분 사이 값만 허용.
if(minute < 0 || minute > 59) {
errorPrint("분(0~59분 사이) 오류");
return;
}
this.minute = minute;
}
public int getSecond() {
return this.second;
}
public void setSecond(int second) {
//초는 0~59분 사이 값만 허용.
if(second < 0 || second > 59) {
errorPrint("초(0~59분 사이) 오류");
return;
}
this.second = second;
}
public String toString() {
return getHour() + ":" + getMinute() + ":" + getSecond();
}
}
public class MySample1121_6 {
public static void main(String[] args) {
//접근제어자(private, (default), protected, public)
Time t = new Time(16, 40, 31);
System.out.println(t);
t.setHour(t.getHour() + 1); //t.hour = 17;
System.out.println(t); //t대신 t.toString 사용해도 같은의미다.
}
}
** 실습 1121_7 (접근제어자) **
/* 문제)이름, 나이, 직업을 입력받아 입력받은 값을 화면에 출력하며, 이름에 "끝:이 입력되면 종료되는 프로그램 작성. 단, 이름/나이/직업과 관련된 정보는 메서드를 사용하여 작성.(private) 문자열비교 : 변수명.equals("끝") 이름.나이.직업을 관리하는 클래스는 Person3 으로 하며, 예외처리 : 프로그램 종료여부와 정보출력(출력예) 메서드는 msgPrint() 입력예)이름은 > 홍길동 나이는 > 23 직업은 > 프로그래머 출력예)홍길동님의 나이는 23살이며, 직업은 프로그래머 입니다.
입력예)이름은 > 끝 나이는 > 22 직업은 > 백수 출력예)프로그램을 종료합니다. */
import java.util.Scanner;
/* 1
문제)이름, 나이, 직업을 입력받아 입력받은 값을 화면에 출력하며, 이름에 "끝:이 입력되면 종료되는 프로그램 작성.
단, 이름/나이/직업과 관련된 정보는 메서드를 사용하여 작성.(private)
문자열비교 : 변수명.equals("끝") //String 타입 비교 (문자열)
이름.나이.직업을 관리하는 클래스는 Person3 으로 하며, 예외처리 : 프로그램 종료여부와 정보출력(출력예) 메서드는 msgPrint()
입력예)이름은 > 홍길동
나이는 > 23
직업은 > 프로그래머
출력예)홍길동님의 나이는 23살이며, 직업은 프로그래머 입니다.
입력예)이름은 > 끝
나이는 > 22
직업은 > 백수
출력예)프로그램을 종료합니다.
*/
class Person3{
private String name, job;
private int age;
public String getName(){
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
public String getJob(){
return this.job;
}
public void setJob(String job) {
this.job = job;
}
//프로그램 종료여부와 출력
public boolean msgPrint() {
if(getName().equals("끝")) {
System.out.println("프로그램 종료합니다.");
return true;
}
else {
System.out.println(getName() + "님의 나이는 " + getAge() + "살이며, 직업은 " + getJob()+ "입니다.");
return false;
}
}
// //위 boolean을 int로 사용할 경우 while(msgPrint()==1)로 쓴다.
// public int msgPrint() {
// if(getName().equals("끝")) {
// System.out.println("프로그램 종료합니다.");
// return 1;
// }
// else {
// System.out.println(getName() + "님의 나이는 " + getAge() + "살이며, 직업은 " + getJob()+ "입니다.");
// return 0;
// }
// }
}
public class MyProject1121_7 {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
//접근제어자
Person3 p3 = new Person3();
//Person3 p3 = null; //다른방법1
while(true) {
//p3 = new Person3(); //다른방법1
System.out.print("이름은 > ");
p3.setName(scn.next()); //nextLine은 엔터키를 가지고 있기에 next()적용
System.out.print("나이는 > ");
p3.setAge(scn.nextInt());
System.out.print("직업은 > ");
p3.setJob(scn.next());
if(p3.msgPrint()) {
break;
}
// nextInt 와 next 는 공백도 자른다. nextLine은 엔터키를 가지고 있다.
}
}
}
이렇게 0과 1의 조함으로 구성된코드를 바이너리(binary) 코드, 즉 기계어라고 한다.
- 사람이 작성한 소스코드를 컴퓨터가 이해하려면 컴퓨터가 이해할 수 있는 언어인 기계어로 변환해야 한다.
· 저급 언어 : 하드웨어 지향의 기계 중심언어 ex) 기계어, 어셈블리어
· 고급 언어 : 사람이 이해하고 작성하기 쉬운 사람 중심 언어 ex) JAVA , C, C++, FORTRAN, COBOL..
▶ 자바 (Java) 란?
- 객체 지향 프로그래밍 언어
- 개발도구(JDK) + 실행환경(JRE) + 라이브러리(API) 를 제공.
▶자바 (Java)의 특징
- 객체지향언어 (상속, 캡슐화, 다형성)
- 운영체제(윈도우,리눅스,유닉스,,,)에 독립적이다. (= 이식성이 높다)
→ JAVA는 JVM(java virtual machine) 위에서 돌아가기 때문 (다른언어는 운영체제에서 돌아감) - C++에서 연산자.기본구분 + 스몰톡에서 객체지향언어관련 구문 가져옴 - Garbage Collection(GC.자동 메모리 관리) → 자동적으로 메모리 관리를 해줌 : 프로그래머가 따로 관리 불필요 - 멀티쓰레드 지원 (하나의 프로그램에서 동시에 여러 작업 가능)
- 네트워크와 분산처리지원
* Java SE (Standard Addition)
- JDK(java development Kit) : 자바 개발 키트
- JRE(Java Runtime Environment) : 자바 실행 환경 - JVM(Java Virtual Machine) -> 자바를 실행하기 위한 가상 머신 (JDK를 설치하면 포함되어 있다.)
· Java는 OS가 달라도 각 OS의 환경에 맞게 번역해주는 JVM만 있으면 동일하게 번역된 결과 출력 가능 · 자바로 작성된 애플리케이션은 모두 이 가상컴퓨터(JVM)에서만 실행되기 때문에 자바 애플리케이션이 실행되기 위해서는 반드시 JVM 필요하다.
▶ java 언어 프로그램 기본 구조
** Hello.java 작성 ----(javac.exe)(컴파일)----> Hello.class 생성 ----(java.exe)(실행)----> "Hello World" 출력
·클래스 이름과 파일 이름은 반드시 동일해야 한다.
· 테스트 목적이 아닌 이상 하나의 파일에 하나의 클래스만 작성한다.
· 클래스 이름 : 대문자로 시작하고 새로운 단어가 결합될 때 첫글자를 대문자로 처리한다.(카멜 표기법 camel case)
· 시작블록 : { 종료블록 : } 을 이용하여 클래스의 시작과 끝 알린다.
· public static void main(String[] args) 메소드가 있는 클래스만 실행할 수 있다.
(실행할 모든 코드는 main() 메소드 블록 안에 위치해야 한다.)
▶ java 프로그램 기초 문법
** 메세지 출력
System.out.print("메세지"); //메세지를 출력하고 개행(Enter)처리를 하지 않는다.
System.out.println("메세지"); //메세지를 출력하고 개행(Enter)처리를 한다.
· 세미콜론(;) - 명령종료
· 빨간색 x - 문법 오류 (x에 마우스 포인트를 올리면 어떤 오류인지 자세히 알려준다.)
· 전구모양 빨간색 x - 단순한 오타
· 들여쓰기 단축키 : <Ctrl> + <Shift> + <F> (자바뿐만 아니라 이클립스로 작성한 모든파일 가능 HTML, XML, JSP...)
▶주석문(comment) - 프로그램 설명을 기입하는 것으로 컴파일과 실행을 하지 않음.
// : 한줄주석(뒤부터 한줄만 주석) /* */ : 범위주석, 한줄 혹은 여러줄 주석(/*로 시작해서 */끝날때까지 주석)
ex) /************************************ 주석 처리할 문장 ************************************/
주석 단축키 → // : <Ctrl> + /
/* */ : <Ctrl> + <Shift> + /
- bit : 1 자리 (0 또는 1) - byte = bit 8개 (JAVA는 byte로 컴파일됨) ex) 1byte → 00101000
- ctv.channelUp();을 실행한후 값 유지 (이유 - ctv라는 동일한 인스턴스 객체이기때문 )
** 예제 1117_3 (상속) **
class Person{
void breath() {
System.out.println("숨쉬기");
}
void eat() {
System.out.println("밥먹기");
}
void say() {
System.out.println("말하기");
}
}
class Student extends Person{
void learn() {
System.out.println("공부하기...");
}
}
class Teacher extends Person{
void teach() {
System.out.println("설명하기...");
}
}
public class MySample1117_3 {
public static void main(String[] args) {
//상속_2번 받는 경우
Student s1 = new Student();
s1.breath();
s1.learn();
Teacher t1 = new Teacher();
t1.eat();
t1.breath();
t1.teach();
}
}
** 예제 1117_4 (상속) **
class Point{ //x, y좌표값만
int x;
int y;
Point(){
this(0, 0);
}
Point(int x, int y){
this.x = x;
this.y = y;
}
String getXY() {
return "(" + x + ", " + y + ")"; //문자열 형태로 보내주기 위해 만듬
}
}
class Shape{ //색가지고 그리기만
String color = "black";
void draw() {
System.out.printf("[color = %s] \n", color);
}
}
class Circle extends Shape{
Point center; //??
int r;
Circle(){
//Point p = new Point(0, 0);
//this(p, 100); //this() 는 항상 첫번째 라인에서 호출되어야 함.
this(new Point(0, 0), 100); //new Point(0, 0) -> new 객체생성한 주소값 반환
}
Circle(Point center, int r){
this.center = center;
this.r = r;
}
void draw() {
System.out.printf("[center=(%d, %d), r=%d, color=%s]\n", center.x, center.y, r, color);
}
}
class Triangle extends Shape{
Point[] p = new Point[3]; // 좌표를 배열로 3개 생성함
// Triangle() {
//
// } //메인에서 new Triangle 객체생성할 때 오류안나기 위해 만들어준다.
// 컬파일러 jdk가 생성자 만들어줌 - > 모든 클래스는 생성자가 하나 존재한다.
// jdk는 생성자가 하나라도 존재하면 빈생성자 만들어주기 않기때문에 -> 빈생성자 하나 만들어 줘야한다.
Triangle(Point[] p) { //Point[] 클래스 배열타입을 받겠다는 의미.
System.out.println("before : " + this.p.length);
this.p = p;
System.out.println("after : " + this.p.length);
}
void draw() {
System.out.printf("[p1=%s, p2=%s, p3=%s, color=%s] \n", p[0].getXY(), p[1].getXY(), p[2].getXY(), color);
}
}
public class MySample1117_4 {
public static void main(String[] args) {
//상속_도형그리기
Point[] p = {
new Point(100, 100), //시작 주소값 넘겨줌
new Point(140, 50),
new Point(200, 100)
};
Triangle t = new Triangle(p);
Circle c = new Circle(new Point(150, 150), 50);
//바로 위 선을 분리하여 적용시 (더 직관적이지만 p2메모리가 더 할당되야한다.)
//Point p2 = new Point(150, 150);
//Circle c = new Circle(p2, 50);
t.draw(); //삼각형 그리기
c.draw(); //원그리기
}
}
** 예제 1117_5 **
class Person2{
String name;
String job;
int age;
Person2(String name, String job, int age){
this.name = name;
this.job = job;
this.age = age;
}
}
class Student2 extends Person2{ //생성자 때문에 오류남
int score;
Student2(String name, String job, int score, int age){
// super.name = name;
// super.job = job;
// super.age = age;
super(name, job, age);
this.score = score;
}
void print() {
// System.out.println("이름 : " + super.name + ", 직업 : " + super.job + ", 나이" + super.age + ", 점수" + this.score);
System.out.println("이름 : " + name + ", 직업 : " + job + ", 나이 : " + age + ", 점수 : " + score);
}
}
class Teacher2 extends Person2{
int pay;
Teacher2(String name, String job, int age, int pay){
// super.name = name;
// super.job = job;
// super.age = age;
super(name, job, age); //자식클래스에서 부모클래스의 변수에 값을 넣을때는 부모클래스의 생성자 이용하는 것이 좋다.
this.pay = pay;
}
void print() {
// System.out.println("이름 : " + super.name + ", 직업" + super.job + ", 나이" + super.age + ", 급여" + this.pay); //올바른 문법
System.out.println("이름 : " + name + ", 직업 : " + job + ", 나이 : " + age + ", 급여 : " + pay);
}
}
public class Sample1117_5 {
public static void main(String[] args) {
// 상속
Student2 s1 = new Student2("홍길동", "학생회장", 100, 19);
s1.print();
Teacher2 t1 = new Teacher2("펭수", "본부장", 40, 1000);
t1.print();
}
}
// s1이 바라보는 Person2와 t1이 바라보는 Person2는 다르다.
// super() -> 부모 생성자
// super.~~ -> 부모 인스턴스
** 실습 1117_6 **
/* 1 부모클래스틑 Animal 클래의 멤버변수는 이름, 이동수단, 울음소리, 다리수로 정의 각 멤버변수를 제어하는 메서드도 포함(get, set메서드를 활용하여 변수값 활용) 단, get으로 시작하는 메서드는 해당 클래스에 인스턴스변수 값을 보내주는 것이며, set으로 시작하는 메서드는 해당 클래스에 인스턴스 변수에 값으르 저장하는 것임 Animal 클래스를 상속받은 자식 클래스를 만들어서 각각의 이름, 이동수단, 울음소리, 다리수를 출력하는 프로그램. 클래스는 Dog(강아지), Eagle(독수리), Lion(사자), Cat(고양이) 출력은 name(이름), move(이동수단), cry(울음소리), leg(다리수) 출력예)강아지 이름은 해피이고, 이동방법은 껑충껑충, 울음소리는 멍멍, 다리수는 4입니다. 독수리 이름은 이글이고, 이동방법은 펄럭펄럭, 울음소리는 구구, 다린수는 2입니다. 사자 이름은 어흥이고, 이동방법은 휙휙휙, 울음소리는 어흥어흥, 다리수는 4 입니다. 고양이 이름은 나비이고, 이동방범은 껑충껑충, 울음소리는 야옹야옹, 다리수는 4입니다. 단, 출력은 메인메서드에서 실행 */
class Animal{
String name;
String move;
String cry;
int leg;
Animal(){
}
Animal(String name, String move, String cry, int leg){
this.name = name;
this.move = move;
this.cry = cry;
this.leg = leg;
}
void setName(String name){ //set과 get은 세트로 잘 다닌다. set에서 값을 세팅하고 get에서 return반환값을 보낸다.
this.name = name;
}
String getName(){
return this.name;
}
void setMove(String move){
this.move = move;
}
String getMove(){
return this.move;
}
void setCry(String cry) {
this.cry = cry;
}
String getCry() {
return cry;
}
void setLeg(int leg) {
this.leg = leg;
}
int getLeg() {
return leg;
}
}
class Dog extends Animal{
Dog(String name, String move, String cry, int leg){
super(name, move, cry, leg);
}
}
class Eagle extends Animal{
Eagle(String name, String move, String cry, int leg){
super(name, move, cry, leg);
}
}
class Lion extends Animal{
Lion(String name, String move, String cry, int leg){
super(name, move, cry, leg);
}
}
class Cat extends Animal{
Cat(String name, String move, String cry, int leg){
super(name, move, cry, leg);
}
}
public class MySample1117_6 {
public static void main(String[] args) {
//상속
Animal a = new Animal();
Dog d = new Dog("해피", "껑충껑충", "멍멍", 4);
Eagle e = new Eagle("이글", "펄럭펄럭", "구구", 2);
Lion l = new Lion("어흥", "휙휙휙", "어흥어흥", 4);
Cat c = new Cat("나비", "껑충껑충", "야옹야옹", 4);
System.out.println("강아지 이름은 " + d.getName() + "이고, 이동방법은 " + d.getMove() + ", 울음소리는 " + d.getCry() + ", 다리수는 " + d.getLeg() + "입니다.");
System.out.println("독수리 이름은 " + e.getName() + "이고, 이동방법은 " + e.getMove() + ", 울음소리는 " + e.getCry() + ", 다리수는 " + e.getLeg() + "입니다.");
System.out.println("사자 이름은 " + l.getName() + "이고, 이동방법은 " + l.getMove() + ", 울음소리는 " + l.getCry() + ", 다리수는 " + l.getLeg() + "입니다.");
System.out.println("고양이 이름은 " + c.getName() + "이고, 이동방법은 " + c.getMove() + ", 울음소리는 " + c.getCry() + ", 다리수는 " + c.getLeg() + "입니다.");
}
}
** 선생님 풀이 1117_6 (상속) **
// MySample1117_6의 문제를 선생님 방법
class Animal2{
String name; //이름
String move; //이동수단
String cry; //울음소리
int leg; //다리수
Animal2(){
this("","","",0);
}
Animal2(String name, String move, String cry, int leg){
// this.name = name; //이름
// this.move = move; //이동수단
// this.cry = cry; //울음소리
// this.leg = leg;
//위 주석과 동일한 의미
setName(name);
setMove(move);
setCry(cry);
setLeg(leg);
}
String getName() {
return this.name;
}
void setName(String name) {
this.name = name;
}
String getMove() {
return this.move;
}
void setMove(String move) {
this.move = move;
}
String getCry() {
return this.cry;
}
void setCry(String cry) {
this.cry = cry;
}
int getLeg() {
return this.leg;
}
void setLeg(int leg) {
this.leg = leg;
}
}
//-Animal 과 Animal을 상속받는 클래스들에 아무것도 없을때 오류가 안나는 이유 - 생성자 하나도 없으면 jdk에서 빈 생성자를 각각 하나씩 만들어주기 때문에
class Dog2 extends Animal{
Dog2(){
this("","","",0); //현단계에서 super(); 호출 하지 않게 하는 방법중 하나.
}
Dog2(String name, String move, String cry, int leg){
super(name, move, cry, leg);
}
}
class Eagle2 extends Animal{
Eagle2(){
}
Eagle2(String name, String move, String cry, int leg){
super(name, move, cry, leg);
}
}
class Lion2 extends Animal{
Lion2(){
}
Lion2(String name, String move, String cry, int leg){
super(name, move, cry, leg);
}
}
class Cat2 extends Animal{
Cat2(){
}
Cat2(String name, String move, String cry, int leg){
super(name, move, cry, leg);
}
}
public class MySample1117_7 {
public static void main(String[] args) {
//상속
//강아지 이름은 해피이고, 이동방법은 껑충껑충, 울음소리는 멍멍, 다리수는 4입니다.
Dog2 d = new Dog2("해피","껑충껑충","멍멍",4);
System.out.println("강아지 이름은 " + d.getName() + "이고, 이동방법은 " + d.getMove() + ", 울음소리는 " + d.getCry() + ", 다리수는 " + d.getLeg() + "입니다.");
Eagle2 e = new Eagle2("이글", "펄럭펄럭", "구구", 2);
System.out.println("독수리 이름은 " + e.getName() + "이고, 이동방법은 " + e.getMove() + ", 울음소리는 " + e.getCry() + ", 다리수는 " + e.getLeg() + "입니다.");
Lion2 l = new Lion2("어흥이", "휙휙", "어흥어흥", 4);
System.out.println("사자 이름은 " + l.getName() + "이고, 이동방법은 " + l.getMove() + ", 울음소리는 " + l.getCry() + ", 다리수는 " + l.getLeg() + "입니다.");
Cat2 c = new Cat2("나비", "껑충꺼충", "야옹야옹", 4);
System.out.println("고양이 이름은 " + c.getName() + "이고, 이동방법은 " + c.getMove() + ", 울음소리는 " + c.getCry() + ", 다리수는 " + c.getLeg() + "입니다.");
}
}
// Generate 실행 예 public String getName() { return name; }
public void setName(String name) { this.name = name; }
class MyMath2{
int j;
int add(int a, int b) {
System.out.println(++j); // ++j 전치연산증감자 (초기값이 0이기때문)
return a + b;
}
int add(int a, double b) {
j++;
System.out.println(j);
return (int)(a + b); //둘다 int로 해도되고 b에만 int 형변환해도된다.
}
int add(double a, int b) {
System.out.println(++j);
return (int)a + b;
}
double add(double a, double b){
System.out.println(++j);
return a + b;
}
int add(int[] a) { //main의 배열 a와 같은 배열아니다.(a(임의로 사용_다른것도 가능)라는 배열을 매개 변수로 받겠다는 의미)
System.out.println(++j);
int i, sum = 0;
for(i = 0 ; i < a.length ; i++) {
sum += a[i];
}
return sum;
}
}
public class MySample1116 {
public static void main(String[] args) {
//메서드 오버로딩
/*
출력예)1
13 (5, 8)
2
12 (5, 7.1)
3
12 (7.1, 5)
4
12.3 (7.1, 5.2)
5
210 (배열)
*/
int[] a = new int[] {10,20,30,40,50,60};
MyMath2 m = new MyMath2();
MyMath2 m2= new MyMath2();
System.out.println(m.add(5,8));
System.out.println(m.add(5,7.1));
System.out.println(m.add(7.1,5));
System.out.println(m.add(7.1,5.2));
System.out.println(m.add(a));
System.out.println("\n");
System.out.println(m2.add(5,3));
System.out.println(m2.add(5,7.1));
System.out.println(m2.add(7.1,5));
System.out.println(m2.add(7.1,5.2));
System.out.println(m2.add(a));
** 메소드 오버로딩1115_2 **
//메서드 오버로딩 /* 실행결과)컴퓨터 가격은 : 10000원 입니다. 제품은 : 컴퓨터 입니다. 구매한 제품은 : 컴퓨터 이며, 10000원 입니다. */
class Computer{
void show(int a){
System.out.printf("컴퓨터 가격은 : %d원 입니다. \n", a);
}
void show(String a) {
System.out.printf("제품은 : %s 입니다. \n", a);
}
void show(String a, int b) {
System.out.printf("구매한 제품은 : %s 이며, %d원 입니다.", a, b);
}
}
public class MySample1116_2 {
public static void main(String[] args) {
//메서드 오버로딩
/*
실행결과)컴퓨터 가격은 : 10000원 입니다.
제품은 : 컴퓨터 입니다.
구매한 제품은 : 컴퓨터 이며, 10000원 입니다.
*/
Computer c = new Computer();
c.show(10000);
c.show("컴퓨터");
c.show("컴퓨터", 10000);
}
}
* 클래스 변수와 메서드, 인스턴스 변수와 메서드
//클래스 변수와 메서드, 인스턴스 변수와 메서드
class Member{
int iv = 10; //인스턴스 변수
static int cv = 20; //클래스 변수
int iv2 = iv; //가능(인스턴스 변수이기 때문에 가능)
// static int cv2 = iv; //불가능(iv는 인스턴스 변수이기 때문에)
//
// Member k = new Member();
// static int cv2 = k.iv; //불가능 (객체생성은 클래스영역말고 메서드에서 해야한다.) (Member객체 생성시기와 static변수 생성시기가 다르기 때문)
//
static int cv2 = new Member().iv; //가능은 하나 사용하지 않은것을 권장
static void staticMethod1() { //클래스 메서드
System.out.println(cv);
System.out.println(iv); //클래스 메소드에서 인스턴스 변수는 사용 불가능
Member k = new Member(); //클래스 메소드에서 인스턴스 변수사용하려면 이렇게 해야한다.
System.out.println(k.iv);
}
void instanceMethod1() { //인스턴스 메서드
System.out.println(cv);
System.out.println(iv);
}
static void staticMethod2() {
staticMethod1();
instanceMethod1(); //클래스 메서드에서 인스턴스 메소드 호출하려면 아래와같이 객체생성 후 가능
Member c = new Member();
c.instanceMethod1();
}
void instanceMethod2() {
staticMethod1();
instanceMethod1();
}
** 생성자 (Constructor) **
- 인스턴스가 생성될 때(new) 호출되는 인스턴스 초기화 메서드
인스턴스 변수의 초기화 작업에 주로 사용
메서드처럼 클래스 내에 선언되며, 리턴값이 없음(void 사용 안함)
- 생성자의 이름은 클래스의 이름과 같아야 함
- 생성자는 리턴 값이 없음
- 생성자에 메소드 오버로딩도 적용 가능하다.
예)
class Card{
Card(){ //매개변수 없는 생성자
...
}
Card(String k, int num){ //매개변수 있는 생성자
...
}
** 예제 **
class Car{
String color;
String gearType;
int door;
Car(){
}
Car(String c, String g, int d){
color = c;
gearType = g;
door = d;
}
}
public class MySample1116_3 {
public static void main(String[] args) {
Car c1 = new Car();
c1.color = "white";
c1.gearType = "auto";
c1.door = 4;
Car c2 = new Car("blue", "auto", 2); //c2.color...에 대입안하고 생성자에 대입함
System.out.println("c1의 color = " + c1.color + ", gearType = " + c1.gearType + ", door = " + c1.door);
System.out.println("c1의 color = " + c2.color + ", gearType = " + c2.gearType + ", door = " + c2.door);
}
}
** 예제 **
public class MySample1116_3 {
public static void main(String[] args) {
//생성자
Data2 d = new Data2();
Data2 d2 = new Data2(10);
System.out.println("d.value : " + d.value);
System.out.println("d2.value : " + d2.value);
}
}
class Data2{
int value;
Data2(){
System.out.println("생성자 Data2() 호풀");
}
Data2(int x){
System.out.println("생성자 Data2(int x) 호풀");
value = x;
}
}
** 실습 1116_3 **
* 두번째
class Car{
String color;
String gearType;
int door;
//두번째
Car(String a){
color = a;
gearType = "Auto";
door = 4;
}
// // 위의 Car(String a)생성자의 매개변수명은 보통 a를 알아보기 쉽게 color로 할 경우
// Car(String color){
// this.color = color; //this.color로하면 그 클래스에 있는 인스턴스변수를 받는다. (변수명이 같을경우 사용하는 this)
// // = 뒤의 color는 매개변수 color를 받는다.
}
Car(){
color = "white";
gearType = "Auto";
door = 4;
}
}
public class MySample1116_3 {
public static void main(String[] args) {
//두번째
//매개변수 1개는 color에 적용. 매개변수 없을 때는 white로 지정
//gearType = auto, door = 4로 지정
System.out.println("main 시작 c1생성");
Car c1 = new Car();
System.out.println("main 시작 c2생성");
Car c2 = new Car("blue");
System.out.println("c1의 color = " + c1.color + ", gearType = " + c1.gearType + ", door = " + c1.door);
System.out.println("c1의 color = " + c2.color + ", gearType = " + c2.gearType + ", door = " + c2.door);
}
}
** 예제 (this.) **
class Car{
String color;
String gearType;
int door;
Car(){
// this.color = "white";
// this.gearType = "auto";
// this.door = 4;
this("white", "auto", 4); //this 같은 클래스 내에서 다른생성자 호출(매개변수 3개를 호출한다는 의미)
System.out.println("매개변수 없음.");
}
Car(String color){
// this.color = color;
// this.gearType = "auto";
// this.door = 4;
this(color, "auto", 4);
System.out.println("매개변수 1개 color");
}
Car(String color, String gearType){ //생성자에서 생성자 호출 가능
// this.color = color;
// this.gearType = gearType;
// this.door = 2;
this(color, gearType, 2);
System.out.println("매개변수 2개 color, gearType");
}
Car(String color, String gearType, int door){
this.color = color;
this.gearType = gearType;
this.door = door;
System.out.println("매개변수 3개");
}
public class MySample1116_3 {
public static void main(String[] args) {
System.out.println("main 시작 c1생성");
Car c1 = new Car(); // 객체생성하면서 매개변수없는 생성자 호출
System.out.println("main 시작 c2생성");
Car c2 = new Car("blue");
System.out.println("main 시작 c3생성");
Car c3 = new Car("red", "auto");
System.out.println("c1의 color = " + c1.color + ", gearType = " + c1.gearType + ", door = " + c1.door);
System.out.println("c2의 color = " + c2.color + ", gearType = " + c2.gearType + ", door = " + c2.door);
System.out.println("c3의 color = " + c3.color + ", gearType = " + c3.gearType + ", door = " + c3.door);
}
}
결과
main 시작 c2생성 매개변수 3개 매개변수 1개 color main 시작 c3생성 매개변수 3개 매개변수 2개 color, gearType c1의 color = white, gearType = auto, door = 4 c2의 color = blue, gearType = auto, door = 4 c3의 color = red, gearType = auto, door = 2
** 예제 1116_4 **
* 생성자를 이용한 인스턴스 복사
class Car1{
String color;
String gearType;
int door;
Car1(){
this("white", "auto", 6); //생성자에서 다른생성자 호출시(this) 항상 첫번째줄에 와야한다.
this.color = "white";
this.gearType = "auto";
this.door = 6;
}
Car1(Car1 c){ //매개변수가 객체(참조형 변수)
this(c.color, c.gearType, c.door);
// this.color = c.color;
// this.gearType = c.gearType;
// this.door = c.door;
}
Car1(String color, String gearType, int door){
this.color = color;
this.gearType = gearType;
this.door = door;
}
}
public class MySample1116_4 {
public static void main(String[] args) {
//생성자 - 생성자를 이용한 인스턴스 복사
Car1 c1 = new Car1();
Car1 c2 = new Car1(c1);
Car1 c3 = new Car1(c1);
System.out.println("c1 color = " + c1.color + ", gearType = " + c1.gearType + ", door = " + c1.door);
System.out.println("c2 color = " + c2.color + ", gearType = " + c2.gearType + ", door = " + c2.door);
System.out.println("c3 color = " + c3.color + ", gearType = " + c3.gearType + ", door = " + c3.door);
c1.door = 50;
c2.color = "pink";
System.out.println("c1 color = " + c1.color + ", gearType = " + c1.gearType + ", door = " + c1.door);
System.out.println("c2 color = " + c2.color + ", gearType = " + c2.gearType + ", door = " + c2.door);
System.out.println("c3 color = " + c3.color + ", gearType = " + c3.gearType + ", door = " + c3.door);
}
}
** 예제 1116_5 **
* 클래스 초기화 블럭 / 인스턴스 초기화 블럭
public class MySample1116_5 {
// static int cv = 1;
// int iv = 2;
//
// //클래스 초기화 블럭 (생성자보다 먼저 실행됨) -> 한번만실행
// static {
// System.out.println("static 초기화영역");
// cv = 10;
// }
//
// //인스턴스 초기화 블럭 -> new 생길때 실행
// {
// System.out.println("인스턴스 초기화 영역");
// iv = 20;
// }
//
// MySample1116_5(){
// System.out.println("MySample1116_5() 생성자호출");
// }
// public static void main(String[] args) {
//
// //초기화 블럭
// System.out.println("main 메서드 시작");
// MySample1116_5 m1 = new MySample1116_5();
//
// System.out.println("main메서드 두번째 실행");
// MySample1116_5 m2 = new MySample1116_5();
//
// System.out.println("main 메서드 끝");
//
// }
public static void main(String[] args) {
Product p1 = new Product();
Product p2 = new Product();
Product p3 = new Product();
System.out.println("p1 제품번호 serialNo : " + p1.serialNo);
System.out.println("p2 제품번호 serialNo : " + p2.serialNo);
System.out.println("p3 제품번호 serialNo : " + p3.serialNo);
System.out.println("객체 생성 수 : " + Product.count);
}
}
class Product{
static int count = 0;
int serialNo;
{
System.out.println("인스턴스 초기화 블럭 시작 count : " + count + ", sreialNo : " + serialNo);
++count;
serialNo = count;
System.out.println("인스턴스 초기화 블럭 끝 count : " + count + ", sreialNo : " + serialNo);
}
Product(){
System.out.println("Product() 생성자");
}
}
** 예제 1116_6 **
public class MySample1116_6 {
public static void main(String[] args) {
//초기화 블럭
/*
출력예)Static method : 1
Static block : 2
Static method : 3
instance method : 4
instance block : 5
instance method : 6
constructor : 7
instance method : 8
instance block : 9
instance method : 10
constructor : 11
*/
STest.test();
STest a = new STest();
STest b = new STest();
}
}
class STest{ //클래스 영역에 정의된 변수는 초기화(입주청소) 해준다.
static int cnt;
static { //클래스 초기화 영역
test(); //test();만 보고 클래스 메서드인것과 같은 클래스내에 정의되어있다를 알 수 있음.
cnt++;
System.out.println("static block : " + cnt);
}
{ //인스턴스 초기화 영역
instanceMethod();
cnt++;
System.out.println("instance block : " + cnt);
}
STest(){
instanceMethod();
cnt++;
System.out.println("constructor : " + cnt);
}
static void test() {
cnt++; //클래스 변수임을 알 수 있다.
System.out.println("static method : " + cnt);
}
void instanceMethod() {
cnt++;
System.out.println("instance method : " + cnt);
}
}
// 생성자 객체 생성 (입주청소) -> 인스턴스 초기화 블럭 실행 -> 생성자 실행
class Data
{
int x;
int y;
}
public class MySample {
//객체지향프로그램 = 기본형 매개변수 시작
public static void main(String[] args) {
Data d = new Data();
d.x = 10;
System.out.println("main() x : " + d.x);
change(d.x);
//클래스or인스턴스명이 앞에 안와도 괜찮은 이유 : 같은 클래스 내에 있는 클래스메소드(static) 호출이기때문
System.out.println("main() after x : " + d.x);
}
//기본형 매개변수
static void change(int x) //void : change 끝났을 때 반환되는 값이 없다.
{
x = 1000;
System.out.println("change() x : " + x);
}
* 참조형 매개변수
class Data
{
int x;
int y;
}
public class MySample {
//참조형 매개변수 시작
public static void main(String[] args)
{
Data d = new Data();
d.x = 10;
System.out.println("main() x : " + d.x);
change(d);
System.out.println("main() after x : " + d.x);
}
static void change(Data d)
{
d.x = 1000;
System.out.println("change() x : " + d.x);
}
}
* 참조형 반환타임(return) + 참조형 매개변수
class Data
{
int x;
int y;
}
public class MySample {
//참조형 반환타입(리턴타입) 시작
public static void main(String[] args)
{
Data d = new Data();
d.x = 10;
Data d2 = change(d);
System.out.println("d.x = " + d.x);
System.out.println("d2.x = " + d2.x); //d.x와 d2.x의 값은 동일하지만 서로다른 주소값이다.
}
static Data change(Data d)
{
Data tmp = new Data();
tmp.x = d.x ;
return tmp;
}
}
* 참조형 반환타입 / 기본형 매개변수
class Data
{
int x;
int y;
}
public class MySample {
//매개변수는 기본현, 반환타입(return타입) 참조형 시작
public static void main(String[] args)
{
int a = 5;
Data d;
System.out.println("main() a : " + a);
d = change(a);
System.out.println("main() after d.x : " + d.x);
}
static Data change(int a)
{
Data tmp = new Data();
tmp.x = a + 10;
return tmp;
}
//매개변수는 기본현, 반환타입(return타입) 참조형 끝
}
** 실습_참조형 매개변수/참조형 반환타입 **
/* 1 문제)Data객체에 y변수 추가하고 main에서 2개 정수를 입력받아 Data 객체 각 변수에 대입하고. main에서 각 값을 출력한 후 copy 메서드를 통해 값에 2를 곱한 결과를 출력하는 프로그램. 입력예)정수 2개를 입력하세요.>10 20 출력예)main 입력값 d.x = 10, d.y : 20 copy 메서드 d.x = 10, d.y : 20 copy 메서드 tmp.x = 20, tmp.y : 40 main 마지막 d.x = 10, d.y : 20 main 마지막 d2.x = 20, d2.y : 40 */
import java.util.Scanner;
class Data
{
int x;
int y;
}
public class MySample {
public static void main(String[] args)
{
Scanner scn = new Scanner(System.in);
System.out.print("정수 2개를 입력하세요.>");
Data d = new Data();
d.x = scn.nextInt();
d.y = scn.nextInt();
System.out.println("main 입력값 d.x = " + d.x + ", d.y : " + d.y);
copy(d);
Data d2 = copy(d);
System.out.println("main 마지막 d.x = " + d.x + ", d.y : " + d.y);
System.out.println("main 마지막 d2.x = " + d2.x + ", d2.y : " + d2.y);
}
static Data copy(Data d) //main d와 d자체는 다른 주소지만, 두개의 d가 바라보는 주소값은 같다.
{
System.out.println("copy 메서드 d.x = " + d.x + ", d.y : " + d.y);
Data tmp = new Data();
tmp.x = d.x * 2;
tmp.y = d.y * 2;
System.out.println("copy 메서드 tmp.x = " + tmp.x + ", tmp.y : " + tmp.y);
return tmp;
}
}
* 배열을 이용한 참조형 매개변수
public class MySample {
//배열을 이용한 참조형 매개변수
public static void main(String[] args)
{
int[] a = {10, 20};
System.out.println("main() a[0] : " + a[0]);
change(a);
System.out.println("main() a[0] : " + a[0]);
}
static void change(int[] x)
{
x[0] = 2000;
System.out.println("change() x : " + x[0]);
}
}
** 실습1115 **
/* 2 문제)위와 동일한 형태로 하되 결과는 다르게 구현 출력예)main 입력값 d.x = 10, d.y : 20 copy 메서드 tmp.x = 10, tmp.y : 20 copy 메서드 tmp.x = 20, tmp.y : 40 main 마지막 d.x = 20, d.y : 40 단, copy메서드의 반환타입(리턴타입) 없음. */
import java.util.Scanner;
class Data
{
int x;
int y;
}
public class MySample {
public static void main(String[] args)
{
Scanner scn = new Scanner(System.in);
System.out.print("정수 2개를 입력하세요.>");
Data d = new Data();
d.x = scn.nextInt();
d.y = scn.nextInt();
System.out.println("main 입력값 d.x = " + d.x + ", d.y : " + d.y);
copy(d);
System.out.println("main 마지막 d.x = " + d.x + ", d.y : " + d.y);
}
static void copy(Data tmp)
{
System.out.println("copy 메서드 tmp.x =" + tmp.x + ", tmp.y : " + tmp.y);
tmp.x = tmp.x * 2;
tmp.y = tmp.y * 2;
System.out.println("copy 메서드 tmp.x =" + tmp.x + ", tmp.y : " + tmp.y);
}
}
** 실습1115 **
/* 3 문제)배열에 {3, 2, 1, 6, 5, 4}를 초기값으로 선언후에 오름차순으로 정렬하여 출력하는 프로그램. 단, 각 메서드는 배열출력은 printArr, 배열의 모든 합은 sumArr, 배열 정렬은 sortArr로 선언하여 구현함. sumArr 메서드만 리턴타입이 존재함. 출력예)[3,2,1,6,5,4] [1,2,3,4,5,6] sum = 21 */
//배열은 시작주소와 길이를 같이 가지고 다닌다.
import java.util.Scanner;
//class Data
//{
// int x;
// int y;
//}
public class MySample1115{
/* 3
문제)배열에 {3, 2, 1, 6, 5, 4}를 초기값으로 선언후에 오름차순으로 정렬하여 출력하는 프로그램.
단, 각 메서드는 배열출력은 printArr, 배열의 모든 합은 sumArr,
배열 정렬은 sortArr로 선언하여 구현함.
sumArr 메서드만 리턴타입이 존재함.
출력예)[3,2,1,6,5,4]
[1,2,3,4,5,6]
sum = 21
*/
//배열은 시작주소와 길이를 같이 가지고 다닌다.
public static void main(String[] args)
{
int[] arr = new int[] {3, 2, 1, 6, 5, 4}; //int[] arr = {3, 2, 1, 6, 5, 4}; 이렇게해도된다.
printArr(arr);
sortArr(arr);
printArr(arr);
System.out.println("sum = " + sumArr(arr));
}
static void sortArr(int[] x) //클래스 메서드 | int[] x -> 배열로 받겠다는 의미
{
int i, j, tmp;
for(i = 0 ; i < x.length - 1 ; i++)
{
for(j = i + 1 ; j < x.length ; j++)
{
if(x[i] > x[j])
{
tmp = x[i];
x[i] = x[j];
x[j] = tmp;
}
}
}
}
static void printArr(int[] arr)
{
int i;
System.out.print("[");
for(i = 0 ; i < arr.length ; i++)
{
// //쉼표를 먼저 찍을 경우
// if(i != 0 && i != arr.length)
// System.out.print(", ");
System.out.printf("%d", arr[i]);
if(i != arr.length -1)
System.out.print(", ");
}
System.out.print("] \n");
}
static int sumArr(int[]a)
{
int sum = 0, i;
for(i = 0 ; i < a.length ; i++)
{
sum += a[i];
}
return sum;
}
}
** 실습1115_2 **
//객체지향프로그램 - 참조형 매개변수 /* 4 문제)두 정수를 Add클래스 a, b변수에 입력받은 후 더하기, 뺴기, 곱하기, 나누기 메서드를 이용하여 결과를 모두 main에서 출력하는 프로그램.(결과는 c변수 사용) 단, 더하기 add, 빼기 sub, 곱하기 mul, 나누기 div 로 정의하며, 참조형 매개변수를 활용한 메서드 구현, 전부 반환타입이 없음. 입력예)두 정수를 입력하세요.>5 3 출력예)더하기 : 8 뺴기 : 2 곱하기 : 15 나누기 : 1 */
import java.util.Scanner;
class Add
{
int a;
int b;
int c;
}
public class MySample1115_2 {
public static void main(String[] args) {
//객체지향프로그램 - 참조형 매개변수
/* 4
문제)두 정수를 Add클래스 a, b변수에 입력받은 후 더하기, 뺴기, 곱하기, 나누기 메서드를 이용하여
결과를 모두 main에서 출력하는 프로그램.(결과는 c변수 사용)
단, 더하기 add, 빼기 sub, 곱하기 mul, 나누기 div 로 정의하며,
참조형 매개변수를 활용한 메서드 구현, 전부 반환타입이 없음.
입력예)두 정수를 입력하세요.>5 3
출력예)더하기 : 8
뺴기 : 2
곱하기 : 15
나누기 : 1
*/
Scanner scn = new Scanner(System.in);
System.out.print("두 정수를 입력하세요.>");
Add ad = new Add(); //Add 클래스의 인스턴스 객체 생성
ad.a = scn.nextInt();
ad.b = scn.nextInt();
add(ad);
System.out.println("더하기 : " + ad.c);
sub(ad);
System.out.println("빼기 : " + ad.c);
mul(ad);
System.out.println("곱하기 : " + ad.c);
div(ad);
System.out.println("나누기 : " + ad.c);
}
static void add(Add a){
a.c = a.a + a.b;
}
static void sub(Add ad){
if (ad.a > ad.b)
ad.c = ad.a - ad.b;
else
ad.c = ad.b - ad.a;
}
static void mul(Add ad){
ad.c = ad.a * ad.b;
}
static void div(Add ad){
ad.c = ad.a / ad.b;
}
}
** 실습1115_2 **
//참조형 매개변수를 이용한 메서드를 Add 클래스에 구현한 경우
//참조형 매개변수를 이용한 메서드를 Add 클래스에 구현한 경우
class Add{
int a;
int b;
int c;
static void add(Add a){
a.c = a.a + a.b;
}
static void sub(Add ad){
if (ad.a > ad.b)
ad.c = ad.a - ad.b;
else
ad.c = ad.b - ad.a;
}
static void mul(Add ad){
ad.c = ad.a * ad.b;
}
void div(Add ad){ //인스턴스 메소드
ad.c = ad.a / ad.b;
}
}
//참조형 매개변수를 이용한 메서드를 Add 클래스에 구현한 경우
public class MySample1115_2 {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
System.out.print("두 정수를 입력하세요.>");
Add ad = new Add(); //Add 클래스의 인스턴스 객체 생성
ad.a = scn.nextInt();
ad.b = scn.nextInt();
Add.add(ad);
System.out.println("더하기 : " + ad.c);
Add.sub(ad);
System.out.println("빼기 : " + ad.c);
Add.mul(ad);
System.out.println("곱하기 : " + ad.c);
ad.div(ad);
System.out.println("나누기 : " + ad.c);
}
}
** 메서드 오버로딩 (overloading) **
한 클래스 내에 같은 이름의 메서드를 여러개 정의
메서드 이름이 같아야 함
매개변수의 개수 또는 타입이 다르게 구현
반환 타입은 오버로딩을 구현하는데 아무런 영향을 주지 못함
예 : System.out.println 메서드
매개변수로 지정하는 값의 타팁에 따라 호출되는 println메서드가 다름
void println()
** 실습1115_3 **
public class MySample1115_3 {
public static void main(String[] args) {
//메서드 오버로딩
MySample1115_3 m = new MySample1115_3();
System.out.println("sum()메서드 매개변수 2개 : " + m.sum(5, 8));
System.out.println("sum()메서드 매개변수 3개 : " + m.sum(1, 2, 3));
m.sum(2);
}
int sum(int a, int b){
return a + b;
}
void sum(int a) {
System.out.println("sum()메서드 1개 a : " + a);
}
int sum(int a, int b, int c){
return a + b + c;
}
}
** 실습1115_4 **
// 메소드 오버로딩
class MyMath{
int a;
int b;
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int multiply(int a, int b) {
return a * b;
}
int divide(int a, int b) {
return a / b;
}
int add() {
return a + b;
}
int subtract() {
return a - b;
}
int multiply() {
return a * b;
}
int divide() {
return a / b;
}
}
public class MySample1115_4 {
public static void main(String[] args) {
//메서드 오버로딩
MyMath m = new MyMath();
m.a = 200;
m.b = 100;
System.out.println(m.add(200, 100));
System.out.println(m.subtract(200, 100));
System.out.println(m.multiply(200, 100));
System.out.println(m.divide(200, 100));
System.out.println(m.add());
System.out.println(m.subtract());
System.out.println(m.multiply());
System.out.println(m.divide());
}
}
** 실습1115_5 **
//메서드 오버로딩 /* 출력예)Java a : 100 a : 89 b : 99 double a : 99.12 total rest 결과 : 198.24 (바로 위 99.12 * 2 한 값) 단, 인스턴스변수 없음 */
class OverLoad1{
int a, b;
void test() {
System.out.println("Java");
}
void test(int a) {
System.out.println("a : " + a);
}
void test(int a, int b) {
System.out.println("a : " + a + " b : " + b);
}
double test(double a) {
System.out.println("double a : " + a);
return a * 2;
}
}
public class MySample1115_5 {
public static void main(String[] args) {
//메서드 오버로딩
/*
출력예)Java
a : 100
a : 89 b : 99
double a : 99.12
total rest 결과 : 198.24 (바로 위 99.12 * 2 한 값)
단, 인스턴스변수 없음
*/
OverLoad1 o = new OverLoad1();
double t;
o.test();
o.test(100);
o.test(89, 90);
t = o.test(99.12); // t = 의 뜻은 o.test(99.12)에 리턴이있다는 의미.
System.out.println("total rest 결과 : " + t);
}
}
import java.util.Scanner;
class Math2
{
//인스턴스 메서드
int add(int a, int b)
{
System.out.println("add메서드 시작 : a = " + a + ", b = " + b);
a = a + 10;
b = b + 10;
int result = a + b;
System.out.println("add메서드 끝 : a = " + a + ", b = " + b);
return result;
}
}
public class MySample1114_2 {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
//계산기 클래스
System.out.print("정수 2개를 입력하세요.>");
int a = scn.nextInt();
int b = scn.nextInt();
System.out.println("main 메서드 호출 전 : a = " + a + ", b = " + b);
Math2 m = new Math2();
int c = m.add(a, b);
System.out.println("main 메서드 호출 후 : a = " + a + ",b = " + b + ", c = " + c);
}
}
** 실습 1114_2 **
/* 1 문제)두 정수를 입력받아 더하기, 빼기, 곱하기, 나누기 연산결과 출력. 입력예)두 정수를 입력하세요.>5 3 출력예)add(a, b) = 8 subtract(a, b) = 2 multiply(a, b) = 15 divide(a, b) = 1.66666666666667(소수점은 실수로 표련 - double) 단, 클래스는 Math3로 한다. */
import java.util.Scanner;
class Math3
{
int add(int a, int b)
{
return a + b;
}
int subtract(int a, int b)
{
//항상 큰수에서 작은수를 뺄수있게 처리
if(a > b)
return a - b;
else //return을 하려면 모든경우가 들어가야한다 -> esle 안쓰면 오류난다.
return b - a;
}
int multiply(int a, int b)
{
return a * b;
}
double divide(int a, int b)
{
return (double)a / b;
}
}
public class MySample1114_2 {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
System.out.print("두 정수를 입력하세요.>");
int a = scn.nextInt();
int b = scn.nextInt();
Math3 m3 = new Math3();
int i = m3.add(a, b);
int j = m3.subtract(a, b);
int k = m3.multiply(a, b);
double l = m3.divide(a, b);
System.out.println("add(a, b) = " + i);
System.out.println("subtract(a, b) = " + j);
System.out.println("multiply(a, b) = " + k);
System.out.println("divide(a, b) = " + l);
//변수 선언 안하고 바로 프린트
System.out.println("add(a, b) = " + m3.add(a, b));
System.out.println("subtract(a, b) = " + m3.subtract(a, b));
System.out.println("multiply(a, b) = " + m3.multiply(a, b));
System.out.println("divide(a, b) = " + m3.divide(a, b));
}
}
** 실습 1114_2 **
//위 문제를 인스턴스변수를 이용하여 더하기, 빼기, 곱하기, 나누기 연산결과 출력.
import java.util.Scanner;
class Math3
{
int a, b;
int add()
{
return a + b;
}
int subtract()
{
//항상 큰수에서 작은수를 뺄수있게 처리
if(a > b)
return a - b;
else //return을 하려면 모든경우가 들어가야한다 -> esle 안쓰면 오류난다.
return b - a;
}
int multiply()
{
return a * b;
}
double divide()
{
return (double)a / b;
}
}
public class MySample1114_2 {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
Math3 m3 = new Math3();
System.out.print("두 정수를 입력하세요.>");
int a = scn.nextInt();
int b = scn.nextInt();
m3.a = a;
m3.b = b;
// int a = scn.nextInt(); / m3.a = a; 합쳐서 사용
m3.a = scn.nextInt();
m3.b = scn.nextInt();
System.out.println("add(a, b) = " + m3.add());
System.out.println("subtract(a, b) = " + m3.subtract());
System.out.println("multiply(a, b) = " + m3.multiply());
System.out.println("divide(a, b) = " + m3.divide());
}
}
** 실습 1114_2 **
//위와 동일한 결과로 클래스 변수를 이용한 계산기 //Math3 클래스에대한 객체인스턴스 m1, m2에 대해서 정의한 후 //m1과 m2에서 각각 같은 변수를 공유한다는 의미로 출력 //클래스 변수병은 기존 소스를 수정하여 a, b 그대로 사용
import java.util.Scanner;
class Math3
{
static int a, b;
int add()
{
return a + b;
}
int subtract()
{
//항상 큰수에서 작은수를 뺄수있게 처리
if(a > b)
return a - b;
else //return을 하려면 모든경우가 들어가야한다 -> esle 안쓰면 오류난다.
return b - a;
}
int multiply()
{
return a * b;
}
double divide()
{
return (double)a / b;
}
}
public class MySample1114_2 {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
System.out.print("두 정수를 입력하세요.>");
Math3.a = scn.nextInt();
Math3.b = scn.nextInt();
Math3 m1 = new Math3();
Math3 m2 = new Math3();
System.out.println("add(a, b) = " + m1.add());
System.out.println("subtract(a, b) = " + m1.subtract());
System.out.println("multiply(a, b) = " + m1.multiply());
System.out.println("divide(a, b) = " + m1.divide());
System.out.println("add(a, b) = " + m2.add());
System.out.println("subtract(a, b) = " + m2.subtract());
System.out.println("multiply(a, b) = " + m2.multiply());
System.out.println("divide(a, b) = " + m2.divide());
}
}
** 스택 & 큐 **
* 스택
데이터를 일시적으로 저장하기위해 사용하는 자료구조로, 데이터이 입력과 출력순서는 후입선루 (LIFO.Last In First Out)
/* 1 문제)정수 2개를 입력받아 메서드 호출전과 후에 대한 결과를 출력하는 프로그램 작성 입력예)정수 2개를 입력하세요.>5 10 출력예)호출 전 a : 5, b : 10 (main메서드에서 출력) add 메서드 a : 10, b : 20 (add메서드에서 출력) 결과 : 30 (main메서드에서 출력) 호출 후 a : 5, b : 10 (main메서드에서 출력) */
import java.util.Scanner;
class Math4
{
int add(int a, int b)
{
a = a * 2;
b = b * 2;
int result = a + b;
System.out.println("add 메서드 a : " + a + ", b : " + b);
return result;
}
}
public class MySample1114_3 {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
System.out.print("정수 2개를 입력하세요.>");
int a = scn.nextInt();
int b = scn.nextInt();
System.out.println("호출 전 a : " + a + ", b : " + b);
Math4 x = new Math4();
// x.add(a, b);
System.out.println("결과 : " + x.add(a, b));
System.out.println("호출 후 a : " + a + ", b : " + b);
}
}
//위와 동일한 결과로 지역변수가 아닌 인스턴스 변수로 이용시.
import java.util.Scanner;
class Math4
{
//인스턴스 변수 적용시
int a, b;
int add(int a, int b)
{
a = a * 2;
b = b * 2;
int result = a + b;
System.out.println("add 메서드 a : " + a + ", b : " + b);
return result;
}
}
public class MySample1114_3 {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
//위와 동일한 결과로 지역변수가 아닌 인스턴스 변수로 이용시.
Math4 m = new Math4(); //인스턴스 변수쓰려고 객체생성
System.out.print("정수 2개를 입력하세요.>");
m.a = scn.nextInt();
m.b = scn.nextInt();
System.out.println("호출 전 a : " +m. a + ", b : " + m.b);
System.out.println("결과 : " + m.add(m.a, m.b));
System.out.println("호출 후 a : " + m.a + ", b : " + m.b);
}
}
//위와 동일할 결과로 지역변수나 인스턴스 변수가 아닌 클래스변수로 이용시.
import java.util.Scanner;
class Math4
{
//클래스 변수만 이용하여 출력.
static int a, b;
int add()
{
a = a * 2;
b = b * 2;
int result = a + b;
System.out.println("add 메서드 a : " + a + ", b : " + b);
return result;
}
}
public class MySample1114_3 {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
System.out.print("정수 2개를 입력하세요.>");
Math4.a = scn.nextInt();
Math4.b = scn.nextInt();
Math4 m = new Math4();
System.out.println("호출 전 a : " + Math4. a + ", b : " + Math4.b);
System.out.println("결과 : " + m.add(Math4.a, Math4.b));
//m.add(m.a, m.b) 하면 버그남(m에 노란줄 뜬다.)
//m.add(Math4.a, Math4.b)에는 (Math4.a, Math4.b)가 아닌 값만 전달된다.
System.out.println("호출 후 a : " + Math4.a + ", b : " + Math4.b);
}
}