[JAVA] °­ÁÂ 11



|11ÀÏÂ÷|



class ¸â¹öº¯¼ö¿Í method , instance ¸â¹öº¯¼ö¿Í method
classÀÇ ¸â¹ö º¯¼ö¿Í ¸Þ¼Òµå... ±×¸®°í instanceÀÇ ¸â¹ö º¯¼ö¿Í ¸Þ¼Òµå....¿¡ ´ëÇÏ¿© ¾Ë¾Æº¸°Ú½À´Ï´Ù.

class A {
 static int i = 10;
 public static void main(String[] args) {
    System.out.println(i);
 }
}


½ÇÇà°á°ú´Â ´ÙÀ½°ú °°´Ù.
C:\Java ¿¬½À\OOP>java A
10

Áï static Å°¿öµå·Î Á¤ÀÇµÈ º¯¼ö´Â class AÀÇ instance¸¦ »ý¼ºÇÏÁö ¾Ê°í¼­µµ °ªÀ» ¾òÀ» ¼ö°¡ ÀÖ´Ù.

±×·¯¸é method¸¦ staticÀ¸·Î Á¤ÀÇÇغ¸ÀÚ.

class A {
 static void getInfo() {
    System.out.println("class AÀÇ static getInfo() ½ÇÇà");
 }
 public static void main(String[] args) {
    getInfo();
 }
}


½ÇÇà°á°ú´Â ¾Æ·¡¿Í °°´Ù.

C:\Java ¿¬½À\OOP>java A
class AÀÇ static getInfo() ½ÇÇà

Áï staticÀ¸·Î Á¤ÀÇµÈ class AÀÇ method´Â instance¸¦ »ý¼ºÇÏÁö ¾Ê°í¼­µµ ½ÇÇàµÉ ¼ö ÀÖ´Ù.

===========================================================

static method¿¡¼­ instanceº¯¼öÀÇ °ªÀ» »ç¿ëÇÏ´Â °ÍÀº ¾î¶³±î?


class A {
 int i = 10;
 static void getInfo() {
    System.out.println(i);
 }
 public static void main(String[] args) {
    getInfo();
 }
}


ÀÌ·¯ÇÑ °æ¿ì¿¡´Â ÄÄÆÄÀϽà ¿¡·¯°¡ ³­´Ù.
class A¿¡¼­ staticº¯¼ö°¡ ¾Æ´Ñ i¸¦ static methodÀÎ getInfo()¿¡¼­ È£ÃâÀ» ÇÏ´Ï ¿¡·¯°¡ ÀÖ´Ù´Â ¸»ÀÌ ³ª¿Â´Ù.

C:\Java ¿¬½À\OOP>javac A.java
A.java:5: Can't make a static reference to nonstatic variable i in class A.
    System.out.println(i);
                       ^
1 error

Áï, static method      System.out.println(i);
 }
}


½ÇÇà°á°ú´Â ¾Æ·¡¿Í °°´Ù.
Áï instance º¯¼öÀÇ overriding°ú ¸¶Âù°¡Áö·Î static º¯¼öÀÇ overriding¶ÇÇÑ super classÀÇ staticº¯¼öÀÎ I=10À» ¼û±â°í sub classÀÎ class B¿¡¼­ »õ·ÎÀÌ Á¤ÀÇÇÑ i=20ÀÌ ÂüÁ¶µÇ¾î
È­¸é¿¡ Ãâ·ÂµÈ´Ù.

C:\Java ¿¬½À\OOP>java B
20

=========================================================

±×·¯¸é overridingµÈ static º¯¼öÀÇ super class¿¡ Á¸ÀçÇÏ´Â static º¯¼ö¸¦ Ãâ·ÂÇÏ·Á¸é ¾î¶»°Ô ÇÏ¸é µÉ °ÍÀΰ¡ ?


class A {
 static int i = 10;
}

class B extends A {
 static int i = 20;
 public static void main(String[] args) {
    System.out.println(A.i);
 }
}


½ÇÇà°á°ú´Â ´ÙÀ½°ú °°´Ù.
overridingµÈ static º¯¼öÀÇ super classÀÇ static º¯¼ö¸¦ »ç¿ëÇÏ°íÀÚ ÇÑ´Ù¸é static º¯¼ö°¡ ¼Ò¼ÓµÈ class ÀÇ À̸§À» »ç¿ëÇÏ¿© ±¸ÇϸéµÈ´Ù.

C:\Java ¿¬½À\OOP>java B
10

static º¯¼ö°¡ overridingµÇ¾ú´õ¶óµµ class AÀÇ static º¯¼ö i°¡ Ãâ·ÂµÇ¾ú´Ù.

==========================================================

static ¸â¹ö¿¡ ´ëÇÑ ¹Ì¹¦ÇÑ ³»¿ëÀ» ´ã°íÀÖ´Â ¿¹Á¦¸¦ ¸¸µé¾îº¸¾Ò´Ù.


class A {
 static int i=10;
 static boolean b=true;
}

class B extends A {
 static int i=20;
 public static void main(String[] arg) {
    System.out.println(i);
    System.out.println(B.i);
    System.out.println(A.i);
    System.out.println(b);
    System.out.println(B.b);
    System.out.println(A.b);
 }
}


½ÇÇà°á°ú´Â ´ÙÀ½°ú °°´Ù.
ÀÌ·¯ÇÑ ¹®Á¦ÀÇ ´äÀ» ¸ÂÃá´Ù¸é »ó¼ÓÀ» ÀÌÇØÇÑ °ÍÀ̶ó »ý°¢µË´Ï´Ù.
C:\Java ¿¬½À\OOP>java B
20
20
10
true
true
true



´ÙÀ½¿¡´Â Method Overloading¿¡ ´ëÇÑ ³»¿ëÀÌ ¿Ã¶ó¿Ã ¿¹Á¤ÀÔ´Ï´Ù.