Programming/Java2014. 3. 17. 19:49
inner class는
class 안에 class를 생성하여
클래스 안에서만 사용하도록 하는 일종의 임시 객체이다. 

inner class
  - staic inner class
method class
anonymous class

inner Class의 제약사항
변수 중에 static이 하나라도 있으면 static class가 되어야 함

method 안에서 선언할 경우 Local Class라 하며,
static 멤버 변수가 선언될 수 없으며 또한, static Local Class가 될 수 없다.

outer.this.var 식으로 inner 클래스의 외부 클래스 변수에 접속할 수 있다.

inner class에서 static 변수에는 (외부 클래스의) static 변수만이 할당가능하다.

public class InnerEx2 {

class InstanceInner {
}

static class StaticInner {
}

InstanceInner iv = new InstanceInner();
static StaticInner cv = new StaticInner();

static void staticMethod()
{
StaticInner obj2 = new StaticInner();

// InstanceInner obj1 = new InstanceInner();
InnerEx2 outer = new InnerEx2();
InstanceInner obj1 = outer.new InstanceInner();
}
} 
내부 클래스에서 다른 내부 클래스를 선언시
외부 클래스.new 내부 클래스(); 식으로 선언할 수 있다.

void myMethod()
{
int lv = 0;
final int LV = 0;

class LocalInner {
int liv = outerIv;
int liv2 = outerCv;
// int liv3 = lv; <<
int liv4 = LV;
}
}
method내의 Local Class에서는 메소드 내의 변수를 사용할 수 없다.
(메소드가 메모리에 올라가서 구획이 생성되기 전이기에)

Object iv = new Object() {void method() {}};
anonymous class 에서의 메소드 정의

public static void main(String[] args)
{
// TODO Auto-generated method stub
Button b = new Button("Start");
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("ActionEvent occurred!!!");
}
});
} 

instanceof
객체 instanceof class 식으로 사용하며, 상속관계에 있을 경우
해당 객체가 상위 객체를 포함하므로 instanceof에서 true가 되지만
상위 객체를 하위 객체로instanceof 할 경우 false가 된다.

'Programming > Java' 카테고리의 다른 글

java generic  (0) 2014.03.18
java static import  (0) 2014.03.17
java private constructor  (0) 2014.03.14
java abstract / interface & cpp virtual  (0) 2014.03.14
Java / cpp - 다형성(polymorphism) 차이점 (동적 바인딩?)  (0) 2014.03.13
Posted by 구차니
Programming/Java2014. 3. 14. 21:11
class를 객체로 생성하지 못하도록 막는게 private 생성자이다.
어떻게 보면 객체를 생성하지 못하게 하나 싶긴한데...
static method들로 도배되어 굳이 생성될 필요가 없는 클래스라면 아예 객체 생성을 막는 것도 방법이긴 하니까..

 The declaration of the empty constructor prevents the automatic generation of a default constructor. Note that if you do not use an access modifier with the constructor it will still be private by default. However, the privatemodifier is usually used explicitly to make it clear that the class cannot be instantiated.
 

[링크 : http://msdn.microsoft.com/en-us/library/kcfb85a6.aspx
Posted by 구차니
Programming/Java2014. 3. 14. 16:45
abstract는 class이기에 extends로 상속받아 쓰지만
interace는 class가 아니고 impletement로 확장하기 위한 껍데기 이기에 다른 클래스를 상속받을 수 있다.
[링크 : http://silverktk.tistory.com/134]
[링크 : http://alloe.tistory.com/80]

cpp에서는 interface(java)처럼 구현을 강제하기 위해 virtual 키워드를 사용할 수 있다.
[링크 : http://stackoverflow.com/questions/12854778/abstract-class-vs-interface-in-c

--
interface 내에서는 전부 abstract method이기에
abstract 키워드 생략

단, abstract class에서는 일반 method도 있으므로
abstract 키워드 생략 불가
---

An interface can extend multiple interfaces.
A class can implement multiple interfaces.
However, a class can only extend a single class.
Careful how you use the words extends and implements when talking about interface and class.

[링크 : http://docs.oracle.com/javase/specs/jls/se7/html/jls-9.html] 
Posted by 구차니
Programming/Java2014. 3. 13. 21:59
cpp 에서 virtual 로 테스트 해본건 아니라 확인이 필요함

class Parent {
String msg = "Parent 클래스";
public String getMsg() {return msg;}
}

class Child extends Parent {
String msg = "Child 클래스";
public String getMsg(){return msg;}
}

public class OverridingEx {

public static void main(String[] args)
{
// TODO Auto-generated method stub
Child cd = new Child();
System.out.println("cd : " + cd.getMsg());

Parent pt = new Child();
System.out.println("pt : " + pt.getMsg());

Parent ct = new Parent();
System.out.println("ct : " + ct.getMsg());
}
} 

결과는 cpp에서 하던 것과는 좀 다르게
Child() 객체를 Parent의 형으로 변환해주어도 실제 객체는 Parent로 인식하는 것이 아닌 Child로 인식을 한다.
cd : Child 클래스
pt : Child 클래스
ct : Parent 클래스 

이는 자바의 동적 바인딩(Dynamic binding)으로 인해
객체의 원형을 추적하여 원래 연결되어야 할 메소드를 호출하기 때문이다. 

[링크 : http://slsjyh.blog.me/30111917680]



+
기억이 잘 나지 않아 vs2008/cpp g++/cpp로 포팅 후 돌려보았는데
결과가 다르게 나왔다. 아무래도 타입에 따라서 형을 추적하는 수준에는 자바와 cpp에는 차이가 있어 보인다.

#include < iostream >
#include < string >

using namespace std;

string pmsg = "Parent 클래스";
string cmsg = "Child 클래스";

class Parent {
public:
	string getMsg()	{return pmsg;}
};

class Child:Parent {	
public:
	string getMsg()	{return cmsg;}
};

class OverridingEx {
public:
	static void main()
	{
		// TODO Auto-generated method stub
		Child *cd = new Child();
		cout << "cd : " + cd->getMsg() << endl;

		//Child *t = new Child();
		//Parent *pt = (Parent *)t;
		Parent *pt = (Parent *)(new Child());
		cout << "pt : " + pt->getMsg() << endl;

		Parent *ct = new Parent();
		cout << "ct : " + ct->getMsg() << endl;
	}
} ;

int main(int argc, char **argv)
{
		OverridingEx ex;// = new OverridingEx();
		ex.main();

        return 0;
}

cd : Child 클래스
pt : Parent 클래스
ct : Parent 클래스  

하지만 virtual로 가상함수를 만들어 오버로딩 시키면
java와 같이 제대로 동적 바인딩을 통해 실행을 할 수 있다.
class Parent {
public:
virtual string getMsg() {return pmsg;}
};

class Child:Parent {
public:
virtual string getMsg() {return cmsg;}
}; 

cd : Child 클래스
pt : Child 클래스
ct : Parent 클래스 

+
2013.03.14 추가
동적 바인딩은 인스턴스 변수와 스태틱 메소드에 대해서는 적용되지 않는다.
[링크 : http://haneulnoon.tistory.com/90]

'Programming > Java' 카테고리의 다른 글

java private constructor  (0) 2014.03.14
java abstract / interface & cpp virtual  (0) 2014.03.14
Java for문 내 변수는 매번 초기화 된다.  (0) 2014.03.13
Java array  (0) 2014.03.13
java string.intern()  (0) 2014.03.12
Posted by 구차니
Programming/Java2014. 3. 13. 17:25
c 에서는 j가 초기값으로 4만 되고 for문에서 증가가 될 텐데
java에서는 허용을 안하는지 4만 계속 나오게 된다. 
 
public class Test {
public static void main(String args[])
{
for(int i = 0; i<10;i++)
{
int j = 4;
System.out.println(j++);
}
}
} 

4
4
4
4
4
4
4
4
4
4

굳이 하려면 이런식으로 for문 내의 초기화 문을 이용하면 되는데 타입이 하나만 할 수 있는 건 좀 아쉬운 듯..
public class Test {
public static void main(String args[])
{
for(int i = 0, j = 4; i<10;i++)
{
// int j = 4;
System.out.println(j++);
}
}
} 

---
음? 집에와서 vs2008로 cpp / c로 생성해서 해보니
둘다 j 값이 초기화 된다? 어?!?!?

게다가.. gcc도 안되네??! 헉?!?! 머지??!?!?!
원래 안되던 방법인가!?!? ㅠㅠ 


---
그러고 보니.. 이렇게 쓰려면.. static으로 해야지 증가했던거 같기도 하고.. 끄아아.. 
기억이 가물가물 하다 ㅠㅠ 

'Programming > Java' 카테고리의 다른 글

java abstract / interface & cpp virtual  (0) 2014.03.14
Java / cpp - 다형성(polymorphism) 차이점 (동적 바인딩?)  (0) 2014.03.13
Java array  (0) 2014.03.13
java string.intern()  (0) 2014.03.12
java bytecode decompiler - javap  (0) 2014.03.12
Posted by 구차니
Programming/Java2014. 3. 13. 17:18
선언
int array[][]; // c style
int[][] array; // java style
 
2차원 배열에서 1차원과 2차원 각각에 대한 인자갯수 확인
array.length;
array[0].length;

가변배열
int array[][] = new int[N][];

[링크 : http://stackoverflow.com/questions/13383692/for-each-loop-using-2d-array]
[링크 : http://docs.oracle.com/.../java/lang/System.html#arraycopy(java.lang.Object, int, java.lang.Object, int, int)
Posted by 구차니
Programming/Java2014. 3. 12. 21:19
intern()은 메모리 사용을 줄이기 위해 사용한다.

heap에 할당된 내용을
stack영역에 설정된(엄밀하게는 string pool) 변수들을 조회하여
중복내용이 있을 경우 heap의 메모리를 해제하고
string pool의 주소로 치환하여 사용하는 메모리를 줄여준다.

그렇기에 == 연산자를 통한 "동일객체" 비교시 동일한 객체로 인식될 수 있게 된다.
(하지만 변수들을 조회한다는 것 자체가 엄청난 부하...)

[링크 : http://ggaman.tistory.com/918]
[링크 : http://www.mimul.com/pebble/default/2008/01/02/1199269440000.html]
[링크 : http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#intern()]

'Programming > Java' 카테고리의 다른 글

Java for문 내 변수는 매번 초기화 된다.  (0) 2014.03.13
Java array  (0) 2014.03.13
java bytecode decompiler - javap  (0) 2014.03.12
java static initialize  (0) 2014.03.12
java 1.5 이후 추가 for-each / varargs(autoboxing)  (0) 2014.03.11
Posted by 구차니
Programming/Java2014. 3. 12. 19:59
자바는 바이트 코드로 컴파일 된 후, 인터프리터로 실행되는데
컴파일된 class 파일을 덤프하는 자바 디 컴파일러가 javap로 기본 내장되어있다.
물론 출력이 오리지널 java 파일로 나오는건 아니니 디버깅 용도의 덤프수준..

C:\Program Files\Java\jdk1.7.0_51\bin>javap
Usage: javap <options> <classes>
where possible options include:
  -help  --help  -?        Print this usage message
  -version                 Version information
  -v  -verbose             Print additional information
  -l                       Print line number and local variable tables
  -public                  Show only public classes and members
  -protected               Show protected/public classes and members
  -package                 Show package/protected/public classes
                           and members (default)
  -p  -private             Show all classes and members
  -c                       Disassemble the code
  -s                       Print internal type signatures
  -sysinfo                 Show system info (path, size, date, MD5 hash)
                           of class being processed
  -constants               Show static final constants
  -classpath <path>        Specify where to find user class files
  -bootclasspath <path>    Override location of bootstrap class files 

[링크 : http://flowonweb.com/post/29756735269/java-bytecode]
[링크 : http://skyul.tistory.com/334]

'Programming > Java' 카테고리의 다른 글

Java array  (0) 2014.03.13
java string.intern()  (0) 2014.03.12
java static initialize  (0) 2014.03.12
java 1.5 이후 추가 for-each / varargs(autoboxing)  (0) 2014.03.11
JUnit 사용 예  (0) 2014.03.11
Posted by 구차니
Programming/Java2014. 3. 12. 18:18
정적 초기화 / static initalize는 
static member variable에 대한 초기화를 수행하는 루틴이다.

static 변수들의 경우 해당 클래스가 인스턴스화 되어 메모리에 올려지지 않더라도(힙에 할당)
스택에서 바로 실행이 되어야 하는 부분이므로
main문이 실행되기 전에 클래스 초기화를 하며 static에 상주하게 되며
static initialize block을 통해 조금은 더 복잡한 구문을 지원하게 된다. (try-catch등의 복잡한)

어떻게 보면.. 일종의 static 변수들에 대한 constructor 라고 볼 수 있으려나?

public class StaticTest4 {
static
{
System.out.println("Statis init1");
}

static String s = echo("string");
static
{
System.out.println("Statis init2");
}

static String echo(String s)
{
System.out.println(s);
return s;
}

public static void main(String[] args)
{
// TODO Auto-generated method stub
System.out.println("main");
StaticTest4 st4 = new StaticTest4();
}

}
 

결과는 main 문에 들어가기 전에 static 에 대한 초기화를 먼저 수행함을 볼 수 있다.
Static init1
string
Static init2
main 

[링크 : http://raoo.tistory.com/54]
[링크 : http://cafe.naver.com/hanbitria/15]

 This works well when the initialization value is available and the initialization can be put on one line. However, this form of initialization has limitations because of its simplicity. If initialization requires some logic (for example, error handling or a for loop to fill a complex array), simple assignment is inadequate. Instance variables can be initialized in constructors, where error handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.
[링크 : http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html


'Programming > Java' 카테고리의 다른 글

java string.intern()  (0) 2014.03.12
java bytecode decompiler - javap  (0) 2014.03.12
java 1.5 이후 추가 for-each / varargs(autoboxing)  (0) 2014.03.11
JUnit 사용 예  (0) 2014.03.11
java class default access modifier  (0) 2014.03.11
Posted by 구차니
Programming/Java2014. 3. 11. 20:32
배열은 기존의 for(초기화;조건문;증감문) 식이 아닌
for(변수형:변수 리스트) 식으로 for-each를 통해 간편하게 구현을 할 수 있게 되어 있다.
public void argTest(String... n)
{
//for (int i = 0; i < n.length; i++)
// System.out.println("n[" + i + "]:" + n[i]);
for(String i: n)
System.out.println(i);

System.out.println("-------------------------------");
}

그리고 c에서는 인자를 ... 를 통해서 가변인자를 지원하나
Java는 1.5 부터(JDK 5) varargs를 지원하게 되었다

단, java에서는 ... 내에서는 동일 형에 대해서 만 지원한다.
public void argTest(String... n)

vt.argTest("Varargs", "Test");
vt.argTest("100", "600", "900", "1000");
vt.argTest();

C언어 스타일로 사용하려면 하나의 변수를 고정하고 그 이후에 대해서 ... 처리 하면 되지만
public void argTest(int s, String... n)

vt.argTest(1);
vt.argTest(1,"100");

C언어처럼 ... 이후에는 다른 변수를 추가할 수는 없다.(즉, 다른 형에 대해서는 연속적으로 입력 불가능)
public void argTest(int s, String... n, double e)
Error : The variable argument type String of the method argTest must be the last parameter 

for-each나 ...(varargs)는 autoboxing을 통해 구현되는 것으로 보인다.

[링크 : http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html] for
[링크 : http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html] for - each
[링크 : http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html]
    [링크 : http://docs.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html]
    [링크 : http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html]

'Programming > Java' 카테고리의 다른 글

java bytecode decompiler - javap  (0) 2014.03.12
java static initialize  (0) 2014.03.12
JUnit 사용 예  (0) 2014.03.11
java class default access modifier  (0) 2014.03.11
*.java 파일 하나에 여러개의 class 생성  (0) 2014.03.11
Posted by 구차니