'언어(Language)/JAVA'에 해당되는 글 7건

  1. 2013.12.19 No enclosing instance of type 컴파일 오류
  2. 2013.12.19 Java 한글 <-> 유니코드 변환
  3. 2013.12.18 Text File Read Write
  4. 2013.10.20 IS-A 관계와 HAS-A 관계
  5. 2013.10.20 캡슐화
  6. 2013.10.20 다형성
  7. 2013.10.20 상속
posted by 셀로브 2013. 12. 19. 21:56


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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

No enclosing instance of type 클래스이름 is accessible. Must qualify the 
allocation with an enclosing instance of type 클래스이름 (e.g. x.new A() where 
        x is an instance of 클래스이름)

접근하려는 클래스의 인스턴스가 닫혀져 있지 않다는 뜻인듯합니다.

검색해보니 static 인지 확인하라고 되어 있군요.

참고 : http://www.ezslookingaround.com/blog/tech/?no=1265

    static 메서드 안에 비스테틱 local class를 선언해서 사용하는 경우 발생합니다.
    public class A {
    class B {
    }

    public static String getString(){
        B b = new B();                      //여기서 컴파일 에러가 발생합니다.
    }
}

non-static 클래스는 포함하고있는 상위 클래스를 인스턴스로 생성한다음 그 인스턴스를 통해서 생성할수 있는데 , 
해당 메서드에서는 포함하고 있는 A클래스의 인스턴스를 생성하지 않고  B클래스만 생성하려고 하기 때문입니다.
public class A {
    static class B {
    }

    public static String getString(){
        B b = new B();                      //이제는 별말 안합니다.
    }
}

차라리 public class로 따로 만들어도 됩니다.
//A.java
public class A {
    public static String getString(){
        B b = new B();                      //이래도 별말 안합니다..
    }
}
-----------------------------
//B.java
public class B {

}

그냥 로컬에서만 빼도 됩니다.
//A.java
public class A {
    public static String getString(){
        B b = new B();                      //이래도 별말 안합니다..
    }
}

class B {

}

그리고 둘다 static 을 지워도 됩니다.
public class A {
    class B {
    }

    public String getString(){
        B b = new B();                      //이경우도 별말 안합니다.
    }
}


'언어(Language) > JAVA' 카테고리의 다른 글

Java 한글 <-> 유니코드 변환  (0) 2013.12.19
Text File Read Write  (0) 2013.12.18
IS-A 관계와 HAS-A 관계  (0) 2013.10.20
캡슐화  (0) 2013.10.20
다형성  (0) 2013.10.20
posted by 셀로브 2013. 12. 19. 21:34


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
30
31
32
33
34
35
36
37
38
39
40
public class Unicode {

    public static String decode(String unicode)throws Exception {
        StringBuffer str = new StringBuffer();

        char ch = 0;
        forint i= unicode.indexOf("\\u"); i > -1; i = unicode.indexOf("\\u") ){
            ch = (char)Integer.parseInt( unicode.substring( i + 2, i + 6 ) ,16);
            str.append( unicode.substring(0, i) );
            str.append( String.valueOf(ch) );
            unicode = unicode.substring(i + 6);
        }
        str.append( unicode );

        return str.toString();
    }

    public static String encode(String unicode)throws Exception {
        StringBuffer str = new StringBuffer();

        for (int i = 0; i < unicode.length(); i++) {
            if(((int) unicode.charAt(i) == 32)) {
                str.append(" ");
                continue;
            }
            str.append("\\u");
            str.append(Integer.toHexString((int) unicode.charAt(i)));

        }

        return str.toString();

    }

    public static void main(String[] args) throws Exception {
        String str = encode("한 글");
        System.out.println(str);
        System.out.println(decode(str));
    }
}


'언어(Language) > JAVA' 카테고리의 다른 글

No enclosing instance of type 컴파일 오류  (0) 2013.12.19
Text File Read Write  (0) 2013.12.18
IS-A 관계와 HAS-A 관계  (0) 2013.10.20
캡슐화  (0) 2013.10.20
다형성  (0) 2013.10.20
posted by 셀로브 2013. 12. 18. 19:12

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.io.*;

public class ReadWriteTextFile {

    static public String getContents(File aFile) {
        //...checks on aFile are elided
        StringBuilder contents = new StringBuilder();

        try {
            //use buffering, reading one line at a time
            //FileReader always assumes default encoding is OK!
            BufferedReader input =  new BufferedReader(new FileReader(aFile));
            try {
                String line = null; //not declared within while loop
                /*
                 * readLine is a bit quirky :
                 * it returns the content of a line MINUS the newline.
                 * it returns null only for the END of the stream.
                 * it returns an empty String if two newlines appear in a row.
                 */

                while (( line = input.readLine()) != null){
                    contents.append(line);
                    contents.append(System.getProperty("line.separator"));
                }
            }
            finally {
                input.close();
            }
        }
        catch (IOException ex){
            ex.printStackTrace();
        }


        return contents.toString();
    }

    static public void setContents(File aFile, String aContents)
            throws FileNotFoundException, IOException {
        if (aFile == null) {
            throw new IllegalArgumentException("File should not be null.");
        }
        if (!aFile.exists()) {
            throw new FileNotFoundException ("File does not exist: " + aFile);
        }
        if (!aFile.isFile()) {
            throw new IllegalArgumentException("Should not be a directory: " + aFile);
        }
        if (!aFile.canWrite()) {
            throw new IllegalArgumentException("File cannot be written: " + aFile);
        }

        //use buffering
        Writer output = new BufferedWriter(new FileWriter(aFile));
        try {
            //FileWriter always assumes default encoding is OK!
            output.write( aContents );
        }
        finally {
            output.close();
        }
    }

    public static void main (String... aArguments) throws IOException {
        File testFile = new File("C:\\PageCount.txt");
        System.out.println("Original file contents: " + getContents(testFile));
        setContents(testFile, "The content of this file has been overwritten...");
        System.out.println("New file contents: " + getContents(testFile));
    }
}


'언어(Language) > JAVA' 카테고리의 다른 글

No enclosing instance of type 컴파일 오류  (0) 2013.12.19
Java 한글 <-> 유니코드 변환  (0) 2013.12.19
IS-A 관계와 HAS-A 관계  (0) 2013.10.20
캡슐화  (0) 2013.10.20
다형성  (0) 2013.10.20
posted by 셀로브 2013. 10. 20. 04:46

상속관계 중 IS-A관계와 HAS-A관계가 있다.


말 그대로 IS-A관계는 "~는 ~이다."가 성립되는 관계이고, HAS-A관계는 "~는 ~이다."가 성립되는 관계이다.


다음 상속관계를 살펴보자.

public class Human{

String name; // 이름

int age; // 나이

int sex; // 성별

}

public class Studentextends Human{

int number; // 학번

int major; // 전공

}


위의 상속 관계에서는 학생클래스가 사람클래스를 상속받고 있다.

"학생은 사람이다". 이러한 관계를 위처럼 표현했을 때 IS-A관계 라고 한다.


이어서 다음 상속관계를 살펴보자.

public class Gun{

String name; // 총 이름

int shot; // 총알 수

}

public class Police{

Gun gun; // 멤버객체로 총을 갖는다.

}



위와 같이 "경찰은 총을 가진다."의 구조로 경찰클래스안에 권총클래스의 객체를 멤버로 가지고 있는 경우를 HAS-A 관계라고 한다.

'언어(Language) > JAVA' 카테고리의 다른 글

Java 한글 <-> 유니코드 변환  (0) 2013.12.19
Text File Read Write  (0) 2013.12.18
캡슐화  (0) 2013.10.20
다형성  (0) 2013.10.20
상속  (0) 2013.10.20
posted by 셀로브 2013. 10. 20. 03:47

캡슐화는 중요한 정보를 은닉하여 보호할 수 있도록 구성하는 것입니다. 


가장 간단한 형태의 캡슐화는 다음과 같습니다.

public class Airplane{

private int speed;    // 접근지정자를 private로 지정

public void setSpeed(int speed){

this.speed = speed * 1000;

}

public int getSpeed(){

return speed;

}

}


public class test{

public static void main(String[] args){

Airplane jet = new Airplane();

jet.setSpeed(227);

speed = 227;    // error : 정상적이지 않은 접근을 막아 오류를 막을 수 있습니다.

}

}


즉, 이처럼 올바르지 않은 접근으로부터 자원을 보호할 수 있습니다.

캡슐화를 통해 코드의 부분을 나머지 부분으로부터 분리할 수 있습니다.


'언어(Language) > JAVA' 카테고리의 다른 글

Java 한글 <-> 유니코드 변환  (0) 2013.12.19
Text File Read Write  (0) 2013.12.18
IS-A 관계와 HAS-A 관계  (0) 2013.10.20
다형성  (0) 2013.10.20
상속  (0) 2013.10.20
posted by 셀로브 2013. 10. 20. 03:26

부모클래스 Animal에 자식클래스 Dog, Cat, Duck이 있다.



자식클래스들은 각각 부모클래스의 Speek()함수를 재정의 하고고 있다.

재정의 한 내용은 다음과 같다고 가정하자.


Dog

public void Speek(){

    System.out.println("멍멍 ");

}


Cat

public void Speek(){

    System.out.println("야옹 ");

}


Duck

public void Speek(){

    System.out.println("꽥꽥 ");

}


Dog, Cat, Duck은 Animal의 자식클래스 이므로 다음과 같은 객체생성이 가능하다.


Animal dog = new Dog();

Animal cat = new Cat();

Animal duck = new Duck();


그리고 다음과 같이 함수를 호출해보자.
dog.speek();
cat.speek();
duck.speek();


각각의 자식클래스는 재정의한 speek함수의 동작을 수행하게 된다.


실행결과

 멍멍 야옹 꽥꽥


이처럼 다형성을 활용하면 서로 다른 서브클래스의 객체가 동일한 함수호출로 다른 응답을 하도록 구성할 수 있다.


'언어(Language) > JAVA' 카테고리의 다른 글

Java 한글 <-> 유니코드 변환  (0) 2013.12.19
Text File Read Write  (0) 2013.12.18
IS-A 관계와 HAS-A 관계  (0) 2013.10.20
캡슐화  (0) 2013.10.20
상속  (0) 2013.10.20
posted by 셀로브 2013. 10. 20. 02:37

상속은 중복되는 코드를 피할 수 있는 장점이 있습니다. 하지만 많은 경우 의존도가 높아지는 단점이 있습니다. 다음은 상속의 기본 구조입니다.


부모클래스(Super Class)

public class Airplane{

private int speed;


public Airplane(){

}

public int getSpeed(){

return speed;

}

public void setSpeed(int speed){

this.speed = speed;

}

}


자식클래스(Sub Class)

public class Jet extends Airplane{

private static final int MULTIPLIER = 2;


public Jet(){

super();    // 수퍼클래스(부모클래스)의 생성자를 호출 합니다.

}

public void setSpeed(int speed){    // 함수 오버라이딩 (부모클래스의 멤버함수를 재정의)

super.setSpeed(speed * MULTIPLIER);

}

public void accelerate(){

super.setSpeed(getSpeed() * 2);

}

}


위 상속을 UML로 표현하면 다음과 같습니다.



더 공부하기

캡슐화

다형성

IS-A관계와 HAS-A관계


'언어(Language) > JAVA' 카테고리의 다른 글

Java 한글 <-> 유니코드 변환  (0) 2013.12.19
Text File Read Write  (0) 2013.12.18
IS-A 관계와 HAS-A 관계  (0) 2013.10.20
캡슐화  (0) 2013.10.20
다형성  (0) 2013.10.20