본문 바로가기
2_ 바삭바삭 프로그래밍/Java

Java - 자바기본

by 준환이형님_ 2011. 1. 6.

새로운 프로젝트를 시작하기에 앞서 그 유명한 자바를 배우게 되었죠..ㅋ 전역하신 사로자바 신이 그립군요ㅜ

출처: http://cafe.naver.com/anigocom.cafe?iframe_url=/ArticleRead.nhn%3Farticleid=731
유상철(skinhead101)

 

01. 헬로월드


public class TestMain // 클래스 이름이 파일명과 동일해야 한다.
{
 public static void main(String[] args) // String[] args 매개변수는 반드시 필요하다.
 {
  System.out.println("Hello World!") ; // println() 메서드는 자동으로 개행한다.
 }
}

 

02.데이터형(기본,래퍼,최상위)

public class TestMain
{
 public static void main(String[] args)
 {
  // Java에는 sizeof()기능이 없다. 각 변수에 할당된 숫자가 메모리를 차지하는 비트 수를 나타낸다.
  boolean b = true ;
  byte y = 8 ;
  char c = 'A' ; // Java에서의 char형은 유니코드 기반으로 2바이트(16비트)의 메모리를 차지한다.
  short s = 16 ;
  int n = 32 ;
  long l = 64 ;
  float f = 32.0f ;
  double d = 64.0f ;

  // 기본 데이터형을 객체화시켜주는 래퍼 클래스로 생성자의 매개변수를 통해 초기값을 할당한다.
  Boolean Cb = new Boolean(b) ;
  Byte Cy = new Byte(y) ;
  Character Cc = new Character(c) ;
  Short Cs = new Short(s) ;
  Integer Cn = new Integer(n) ;
  Long Cl = new Long(l) ;
  Float Cf = new Float(f) ;
  Double Cd = new Double(d) ;


  // 출력 테스트.
  System.out.print("boolean: " + b + " / ") ;
  System.out.println("Boolean: " + Cb.booleanValue()) ;

  System.out.print("byte: " + y + " / ") ;
  System.out.println("Byte: " + Cy.byteValue()) ;

  System.out.print("char: " + c + " / ") ;
  System.out.println("Character: " + Cc.charValue()) ;

  System.out.print("short: " + s + " / ") ;
  System.out.println("Short: " + Cs.shortValue()) ;

  System.out.print("int: " + n + " / ") ;
  System.out.println("Integer: " + Cn.intValue()) ;

  System.out.print("long: " + l + " / ") ;
  System.out.println("Long: " + Cl.longValue()) ;

  System.out.print("float: " + f + " / ") ;
  System.out.println("Float: " + Cf.floatValue()) ;

  System.out.print("double: " + d + " / ") ;
  System.out.println("Double: " + Cd.doubleValue()) ;


  // 래핑된 값은 포인터처럼 사용할 수 있다.

  // 자바에서는 다음과 같은 표현이 불가능하다.
  /*
  void* pv = &n ;
  int* pn = (int*)pv ;
  printf("%d \n", *pn) ;
  */
  // 그러므로...

  Object obj = new Integer(n) ; // int n값을 Integer클래스로 래핑하여 void*역할을 하는 Object인스턴스에 보관 후,
  int nValue = ((Integer)obj).intValue() ; // 나중에 Integer형 인스턴스로 형변환하여 intValue()메서드로 값을 리턴받을 수 있다.
  System.out.println("\n래핑되어 Object인스턴스에 들려진 값 추출: " + nValue + "\n\n") ;


  // Java의 true,false,null은 숫자와 별개로 처리된다.
  // 따라서 다음 코드는 에러이다.
  /*
  while(1) ;  ==> 1은 true라고 인식하지 않는다. 따라서 while(true)이렇게 코딩해야한다.
  int n = null ;  ==> null은 0이 아니며 인스턴스(포인터)가 가리키는 객체가 없음을 뜻한다.
  그러므로 기본 데이터형인 int는 null값을 가질 수 없다.
  null의 올바른 사용의 예: Object obj = null ;  ==> obj는 아무것도 가리키고 있지 않음.
  */
 }
}

 

03.자바 클래스(상속,추상,인터페이스,final)

03-1.추상


public abstract class TestAbstract // 추상메서드가 하나라도 있으면 클래스도 반드시 추상클래스여야 한다.
{
 public void testMethod()
 {
 }

 public abstract void testAbstractMethod1() ; // 추상메서드이므로 구현코드를 작성하지 않고 선언만 한다.
 protected abstract void testAbstractMethod2() ; // 인터페이스와 달리 protected는 가능하다.
}

 

03-2.Enum

public enum TestEnum // Enum하나를 만들려 해도 파일하나가 필요하므로 불편하다.
{
 first,
 second,
 third,
} // Enum은 보통 클래스 내부에 inner형태로 만드는 것이 일반적이다. 또는 그냥 C/C++에서처럼 public static final int형 값을 #define값처럼 사용한다.

 

03-3.interface1

public interface TestInterface1
{
 public void testInterfaceMethod1() ; // 인터페이스의 메서드는 무조건 public이다.
 void testInterfaceMethod2() ; // public을 붙이지 않아도 자동으로 붙는다.
}

 

03-4.interface2

public interface TestInterface2
{
 public static final int testInterfaceField1 = 1 ; // 인터페이스의 필드는 무조건 public static final이다.
 int testInterfaceField2 = 2 ; // public static final을 붙이지 않아도 자동으로 붙는다.
}

 

03-5.main


public class TestMain extends TestAbstract
implements TestInterface1, TestInterface2 // 인터페이스는 다중상속이 가능하다.
{
 public static void main(String[] args)
 {
  // 인터페이스의 필드는 상수이므로 다음 코드는 에러이다.
  /*
  TestInterfaceField1 = 3 ;
  TestInterfaceField2 = 4 ;
  */
  // 또한 인터페이스의 상수필드는 사용하기 불편한 enum대신에 많이 사용한다.

  // 메서드 오버라이딩 여부 확인.
  TestSuperClass tc1 = new TestSuperClass() ;
  TestSuperClass tc2 = new TestSubClass() ;
  System.out.println("메서드 오버라이딩 여부 확인.") ;
  tc1.testOverrideMethod() ;
  tc2.testOverrideMethod() ;
  System.out.println() ;
 }


 // 추상클래스 또는 인터페이스를 상속하였을 경우 미구현 메서드들을 반드시 구현해야 한다.
 public void testAbstractMethod1()
 {
 }
 protected void testAbstractMethod2()
 {
 }
 public void testInterfaceMethod1()
 {
 }
 public void testInterfaceMethod2()
 {
 }
}

 

03-6.SubClass
public class TestSubClass extends TestSuperClass
{
 protected void testOverrideMethod() // 오버라이딩 된 메서드.
 {
  System.out.println("자식클래스의 메서드") ;
 }
}

 

03-7.SuperClass


public /*final*/ class TestSuperClass // final이 붙은 메서드는 더 이상 상속이 불가능하도록 봉인된다.
{
 protected void testOverrideMethod() // Java는 virtual키워드가 없으며 자식클래스에 같은 이름의 메서드가 있으면 자동으로 오버라이딩한다.
 {
  System.out.println("부모클래스의 메서드") ;
 }

 protected final void testFinalMethod() // final이 붙은 메서드는 오버라이딩이 불가능하도록 봉인된다.
 {
  System.out.println("부모클래스의 메서드") ;
 }
}