2013. 7. 25. 16:48


■ extends

 : 부모의 모든 멤버를 상속받는다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Parent
{
    String str = "부모멤버";
    public void show()
    {
        System.out.println("부모의 메서드");
    }
}
 
class Child extends Parent
{
    String str = "자식멤버";
    @Override
    public void show()
    {
        System.out.println(super.str);
        System.out.println(this.str);
         
        super.show(); //부모의 메서드, 즉 재정의 하기 전의 메서드를 의미함.
        //this.show();  //무한재귀호출
    }
}
 
new Child().show()
 
부모멤버
자식멤버
부모의 메서드

 

 

 

부모가 있는 클래스에 한해서 super 키워드를 사용할 수 있는데

super는 부모를 의미하는 것이 맞지만 때에 따라선 자식 멤버를 가르키기도 한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Parent
{
    String str = "부모멤버";
}
 
class Child extends Parent
{
    public void show()
    {
        str = "자식이 재정의 한 멤버변수";
        String str = "지역변수";
         
        System.out.println(str);
        System.out.println(this.str);
        System.out.println(super.str);
    }
}
 
new Child().show()
 
지역변수
자식이 재정의 한 멤버변수
자식이 재정의 한 멤버변수

 

 

 부모클래스에 추상클래스가 존재한다면 해당 메서드는 반드시 재정의 해야한다. (하지 않은경우 컴파일 에러 발생)

 

1
2
3
4
5
6
7
8
9
10
11
abstract class Parent
{
    abstract void print();
    public void show() { }
}
 
class Child extends Parent
{
    @Override
    void print() { }
}

 

 

 

스태틱 메서드는 재정의 할 수 없다. 하지만 접근은 가능

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Parent
{
    public static void stM()
    {
        System.out.println("ㅎㅇ");
    }
}
 
class Child extends Parent
{
    public void show()
    {
        stM();
    }
}

 

 


 

■ implements

 : 인터페이스를 구현(구상화)한다.

 : 구현클래스는 인터페이스의 멤버를 반드시 재정의해야한다. 단, 파이널스태틱 멤버는 제외

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
interface I_Parent
{
    String str = null;
        //final static str = null;
        //인터페이스의 멤버 변수는 자동으로 파이널스태틱 변수로 선언됨.
     
    public void result();
    public void excute();
}
 
class Child implements I_Parent
{
    @Override
    public void result() { }
 
    @Override
    public void excute() { }
}

 

 

extends와 implements는 둘 다 상속의 개념이다.

하지만 클래스는 클래스끼리 extends 해야하며 인터페이스 역시 인터페이스끼리 extends 해야함.

implements 는 오직 인터페이스를 구현하는 클래스에만 해당된다.

class Parent { }

class Child extends Parent { }

 

interface I_Parent { }

interface I_Child extends I_Parent { }

 

interface I_Parent { }

class Child implements I_Parent { }

 



■ UpCasting

 : 부모형의 변수에 자식의 인스턴스를 할당할 시

 : 재정의 된 멤버에 한해서 자식의 멤버가 실행우선권을 갖는다. 하지만 보이는것은 부모것

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Parent
{
    public void show()
    {
        System.out.println("부모 메서드");
    }
}
 
 
class Child extends Parent
{
    @Override
    public void show()
    {
        System.out.println("자식 메서드");
    }
}
 
Parent p = new Child();
p.show();

 

 

'java' 카테고리의 다른 글

Enumeration, 열거형  (0) 2013.07.25
Generic, 제네릭  (0) 2013.07.25
팩토리얼(재귀호출)  (0) 2013.07.25
Args, 비정형인자  (0) 2013.07.25
연산자 우선순위  (0) 2013.07.25
Posted by 1+1은?
2013. 7. 25. 16:40


public class Ex77_Recursive {
    public static void main(String[] args) {
 
        //팩토리얼
        //4! = 4 x 3 x 2 x 1 = 24
        //4! = 4 x 3 x 2! = 24
        //4! = 4 x 3! = 24
        //4! = 4! = 24
         
        int result = factorial(4);
        System.out.println(result); 
    }
 
    public static int factorial(int n){
 
        if (n>1)
            return n * factorial(n-1); //재귀호출
        else
            return 1;
    }
}


'java' 카테고리의 다른 글

Generic, 제네릭  (0) 2013.07.25
상속과 구현, 업캐스팅  (0) 2013.07.25
Args, 비정형인자  (0) 2013.07.25
연산자 우선순위  (0) 2013.07.25
제어문  (0) 2013.07.25
Posted by 1+1은?
2013. 7. 25. 16:38

Args, arguments

 : 비정형 인자

 : 매개변수를 배열로 변환하는 키워드



1
2
3
4
5
public void showArgs(int... args)
{
    System.out.println(args[0]);
    System.out.println(args[1]);
}


전달받은 int형 인자값을 args[]배열에 저장하여 배열의 요소를 출력하는 메서드다.

단 이렇게 코드를 작성하면 인자값이 2개가 아닐때 에러가 발생한다. (ArrayIndexOutOfBoundsException)


따라서 런타임 에러를 방지하기 위해선 다음처럼 작성한다.


1
2
3
4
5
6
7
8
public void showArgs(int... args)
{
    for(int i=0; i<args.length; i++)
     //전달받은 인자값만큼 배열의 길이가 결정되므로 그 만큼만 반복
    {
        System.out.println(args[i]);
    }
}

향상된 포문을 활용할 경우 다음과 같다.


1
2
3
4
5
6
7
public void showArgs(int... args)
{
    for(int ns : args)
    {
        System.out.println(ns);
    }
}



다음 예제는 args를 활용한 인자값들의 계산 결과를 구하는 메서드다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Args
{
    public int multiply(int... args)
    {
        int result=1;
         
        for(int ns : args)
        {
            result = result * ns;
        }
         
        return result;
    }
}
 
 
Args a = new Args();
System.out.println(a.multiply(2, 2, 2, 2));
16


1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static void main(String[] args) {
    m1(1, 2, 3); //6
    m1(1, 2, 3, 4); //10
}
     
public static int m1(int... args) {
    int sum = 0;
     
    for(int i=0; i<args.length; i++)
    {
        sum += args[i];
    }
    return sum;
}


'java' 카테고리의 다른 글

상속과 구현, 업캐스팅  (0) 2013.07.25
팩토리얼(재귀호출)  (0) 2013.07.25
연산자 우선순위  (0) 2013.07.25
제어문  (0) 2013.07.25
파일명 일괄변경  (0) 2013.07.25
Posted by 1+1은?
2013. 7. 25. 16:36

System.out.println("ㅇㅇ" instanceof String);  //인스턴스의 클래스를 확인하는 연산자, 불리언을 리턴함

'java' 카테고리의 다른 글

팩토리얼(재귀호출)  (0) 2013.07.25
Args, 비정형인자  (0) 2013.07.25
제어문  (0) 2013.07.25
파일명 일괄변경  (0) 2013.07.25
폴더정보(폴더, 파일의 용량과 갯수) 출력  (0) 2013.07.25
Posted by 1+1은?
2013. 7. 25. 16:34

제어문

 : 프로그램의 코드 실행 흐름을 제어하는 구문(위->아래)

 : 조건, 반복, 분기 등을 통해 흐름을 제어

 

■ 조건문 : if, switch

■ 반복문 : for, 향상된for, while, dowhile

■ 분기문 : continue, break, goto

 

● if

 : 조건을 제시한 뒤 만족하거나 불만족할 때의 코드를 분기하는 제어문

 : 조건은 반드시 boolean

 : if~elseif~else 구간 중 만족하는 조건이 있다면 블럭을 실행하고 if문을 끝낸다.

 : if문은 중첩으로 사용 가능하다 : 제어문 중첩

if(조건식)

{

    ~~

if(조건식) 

              ~~

} else 

              ~~

} else if(조건식)

{

     ~~

} else 

{

     ~~

}

 

 

● switch

 : switch case문, 조건 1개를 갖고 제어를 분기

switch (조건값)

{

case 값1:  // label

실행문;

break;

case 값2:  

실행문;

break;

default: // else와 같다.

실행문;

break;      

}

 

switch (조건값)

{

case 값1

case 값2:

실행문;

break;

}    // 값1, 값2 둘다 같은 블럭을 실행한다. (break가 없어서 가능한 경우)

 

● for

 : 특정 실행 코드 블럭을 원하는 횟수만큼 반복 제어

for(초기식; 조건식; 증감식;) 

{

실행문;

 

● 향상된 for문

for (variable ele : locationEle) {}  //locationEle : 배열 또는 컬렉션

 

 

1
2
3
4
5
6
7
int[] n = new int[] {40,20,10,50,30,60,35,41,23,78} ;
 
for (int i : n) {
    System.out.println(i);
 
//n의 배열 길이만큼 루프를 돌되 각 사이클마다 i에 객체주소를 저장

 

 

다음처럼 배열을 직접 선언하여 사용하기도 한다.

 

 

1
for (String i : new String[] { "+", "-", "*", "/" })

 

 

 

● while

 

 

1
2
3
4
5
6
int n=1; //초기식
while (n < 11) //조건식
{
    System.out.println(n);
    ++n; //증감식
}

 

 

 

● do while

 

 

1
2
3
4
5
6
7
int n = 1;
do
{
    System.out.println(n);
    ++n;
}
while (n<=10); //선실행 후에 조건식을 참조하기 때문에 조건식이 false라도 일단 실행문은 처리된다.

 

 

 

● continue, break

 break : 현재 자신이 속한 제어문을 탈출

 

 

1
2
3
4
5
6
7
8
for(int i=1; i<11; i++)
{
    if(i==5)
    {
        break
    }
    System.out.println(i);
}   //1,2,3,4

 

 

 continue : 현재 자신이 속한 제어문(if문X) 처음으로 되돌아감

 

 

1
2
3
4
5
6
7
8
for(int i=1; i<11; i++)
{
    if(i==5)
    {
        continue
    }
    System.out.println(i);
}   //1,2,3,4,6,7,8,9,10

 

 

 이름 있는 반복문에서 continue

 

 

1
2
3
4
5
6
7
8
9
10
11
loop: for(int i=0; i<10; i++)
{
    System.out.println("x = " + i);
    for(int j=0; j<10; j++)
    {
        System.out.println("j = " + j);
        if(j>=5)
            continue loop; //loop란 이름을 붙인 for문으로 continue
                                                    //break와 성격이 겹치기 때문에 잘 쓰이진 않음.
    }
}

 

 

'java' 카테고리의 다른 글

Args, 비정형인자  (0) 2013.07.25
연산자 우선순위  (0) 2013.07.25
파일명 일괄변경  (0) 2013.07.25
폴더정보(폴더, 파일의 용량과 갯수) 출력  (0) 2013.07.25
피보나치  (0) 2013.07.25
Posted by 1+1은?