* 상속

   - 두 클래스를 조상과 자손으로 관계를 맺어주는 것

   - 공통 부분은 조상에서 관리하고 개별부분은 자손에서 관리

   - 상속은 1:1 로만 이루어진다

   - C 는 조상이 여러명일수 있으나, JAVA 는 조상이 한명



* 포함

   - 한 클래스의 멤버변수로 다른 클래스를 선언

   - 작은 단위의 클래스를 먼저 만들고 , 이 둘을 조합해서 하나의 커다란 클래스를 만듬




* 상속 vs 포함

   - 가능한 한 많은 관계를 맺어주어 재사용성을 높이고 관리하기 쉽게 한다.

   - ' is -a ' 와 ' has -a ' 를 가지고 문장을 만들어본다.



1.
class Shape {
   String color = "blue";
}

class Point {
   int x;
   int y;

   Point() {
      this(0, 0);
   }
 
   Point(int x, int y) {
      this.x = x;
      this.y = y;
   }
}

class Circle extends Shape {
   Point center;
   int r;

   Circle() {
      this(new Point(0, 0), 100);
   }

   Circle(Point center, int r) {
      this.center = center;
      this.r = r;
   }
}

class Triangle extends Shape {
   Point []p;

   Triangle(Point []p) {
      this.p = p;
   }

   Triangle(Point p1, Point p2, Point p3) {
      p = new Point []{p1, p2, p3};
   }
}

class DrawMain {
   public static void main(String[] args) {
      Circle c1 = new Circle();
      Circle c2 = new Circle(new Point(150, 150), 50);

      Point []p = {new Point(100, 100), new Point(140, 50), new Point(200, 100)};

      Triangle t1 = new Triangle(p);

      System.out.println("c1 중점 : "+ c1.center.x +" , "+ c1.center.y);
      System.out.println("c2 반지름 : "+ c2.r);
      System.out.println("t1 꼭지점 : "+ t1.p[0].x +" , "+ t1.p[0].y + " / "
                                                  + t1.p[1].x +" , "+ t1.p[1].y +" /  "
                                                  + t1.p[2].x +" , "+ t1.p[2].y);
   }
}





* Object 클래스

   - 모든 클래스의 최고조상

   - 모든 클래스는 Object 클래스에 정의된 11개의 메서드를 상속받는다.



2.
class Test {
   int a = 10;
}

class Data extends Test {
   int b = 20;
   void add() {
      System.out.println("메서드 호출");
   }
}

class Value extends Data {
   int c = 30;
}

class ExtendsEx2 {
   public static void main(String[] args) {
      Value v = new Value();
      System.out.println(v.toString());
      System.out.println(v);
   }




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

초기화블럭  (0) 2011.01.22
생성자 . this() . this  (0) 2011.01.17
메서드 오버로딩  (0) 2011.01.17
클래스메서드와 인스턴스메서드  (0) 2011.01.17
JVM 의 메모리구조  (0) 2011.01.16
 

클래스 초기화 블럭 : 클래스변수의 복잡한 초기화에 사용되며 클래스가 로딩될 때 실행된다.


인스턴스 초기화 블럭 : 생성자에서 공통적으로 수행되는 작업에 사용되며 인스턴스가 생성될 
                                때 마다
(생성자보다 먼저) 실행된다.





1.
class BlockTest {
   int a;
   static {
      System.out.println("클래스 블럭");  // 클래스 초기화 블럭
   }

   {
      System.out.println("블럭");  // 인스턴스 초기화 블럭
   }

   BlockTest() {
      System.out.println("생성자"); // 생성자를 통해서 초기화
   }

   public static void main(String[] args) 
   {
      BlockTest bt1=new BlockTest();
      BlockTest bt2=new BlockTest();
   }
}

클래스 블럭
블럭
생성자
블럭
생성자



2.
class Product {
   static int count=0;
   int serialNo;
   {
      ++count;
      serialNo=count;  // 밑으로 가도 상관없다.
   }
   Product() { }
}
class ProductTest {
     public static void main(String[] args) {
        Product p1=new Product();
        Product p2=new Product();
        Product p3=new Product();

        System.out.println("p1의 제품번호(serial no)는 "+ p1.serialNo);
        System.out.println("p2의 제품번호(serial no)는 "+ p2.serialNo);
        System.out.println("p3의 제품번호(serial no)는 "+ p3.serialNo);
        System.out.println("생산된 제품의 수는 모두 "+ Product.count +"개 입니다.");
   }
}

p1의 제품번호(serial no)는 1
p2의 제품번호(serial no)는 2
p3의 제품번호(serial no)는 3
생상된 제품의 수는 모두 3개 입니다.



3.
class Document {
   static int count=0;
   String name;
   Document() {
      this("제목없음"+ ++count);   // this() : 같은 클래스의 다른생성자를 호출 
   }
   Document(String name) {
      this.name=name;
      System.out.println("문서 "+ this.name +" 가 생성되었습니다.");
   }
}
class DocumentTest {
   public static void main(String[] args) {
      Document d1=new Document();
      Document d2=new Document("자바.txt");
      Document d3=new Document();
      Document d4=new Document();
   }
}

문서 제목없음1 가 생성되었습니다.
문서 자바.txt 가 생성되었습니다.
문서 제목없음2 가 생성되었습니다.
문서 제목없음3 가 생성되었습니다.

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

상속과 포함  (0) 2011.01.22
생성자 . this() . this  (0) 2011.01.17
메서드 오버로딩  (0) 2011.01.17
클래스메서드와 인스턴스메서드  (0) 2011.01.17
JVM 의 메모리구조  (0) 2011.01.16


* 생성자 : 객체가 생성될 때마다 호출되는 인스턴스 초기화 메서드





1.
class Data1 {
   int value;
}

class Data2 {
   int value;

   Data2(int x) { // 매개변수가 있는 생성자
      value = x;
   }
}

class ConstructorTest {
   public static void main(String[] args) {
      Data1 d1 = new Data1();
      // Data2 d2 = new Data2();   ERROR
   }
}



2.
class Data1 {
   int value;
   Data1() {}      // 기본생성자 (생성자가 하나도 없을때 컴파일러가 자동으로 만들어준다)
}
class Data2 {
   int value;
   Data2(int x) {   // 매개변수가 있는 생성자
      value = x;
   }
   Data2(int x, int y) {   // 오버로딩
      value = x + y;
   }
}

class ConstructorTest {
   public static void main(String[] args) {
      Data1 d1 = new Data1();
      // Data2 d2 = new Data2();   ERROR
   }
}



3.
class Car {
   String color;
   String gearType;
   int door;
   Car() {
      color = "black";
      gearType = "auto";
      door = 4;
   }
   Car(Car c) {
      color = c.color;
      gearType = c.gearType;
      door = c.door;
   }
}

class CarTest {
   public static void main(String[] args) {
      Car c1 = new Car();
      Car c2 = new Car(c1);
      System.out.println("door = "+c1.door);
      System.out.println("door = "+c2.door);

      c1.door = 100;
      System.out.println("door = "+c1.door);
      System.out.println("door = "+c2.door);
   }
}

door = 4
door = 4
door = 100
door = 100


* this() : 생성자, 같은 클래스의 다른 생성자를 호출할때 사용
            다른 생성자 호출은 생성자의 첫 문장에서만 가능





* this : 인스턴스 자신을 가리키는 참조변수. 인스턴스의 주소가 저장되어 있다




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

상속과 포함  (0) 2011.01.22
초기화블럭  (0) 2011.01.22
메서드 오버로딩  (0) 2011.01.17
클래스메서드와 인스턴스메서드  (0) 2011.01.17
JVM 의 메모리구조  (0) 2011.01.16


1.
class OverloadingTest {
   public static void main(String args[]) {
      MyMath3 mm = new MyMath3();
      System.out.println("mm.add(3,3) 결과 : "+ mm.add(3,3));
      System.out.println("mm.add(3L,3) 결과 : "+ mm.add(3L,3));
      System.out.println("mm.add(3,3L) 결과 : "+ mm.add(3,3L));
      System.out.println("mm.add(3L,3L) 결과 : "+ mm.add(3L,3L));
      int []a = {100, 200, 300};
      System.out.println("mm.add(a) 결과 : "+ mm.add(a));
   }
}

class MyMath3 {
   int add(int a, int b) {
      System.out.print("int add(int a, int b) - ");
      return a+b;
   }
   long add(int a, long b) {
      System.out.print("long add(int a, long b) - ");
      return a+b;
   }
   long add(long a, int b) {
      System.out.print("long add(long a, int b) - ");
      return a+b;
   }
   long add(long a, long b) {
      System.out.print("long add(long a, long b) - ");
      return a+b;
   }
   long add(int []a) {
      System.out.print("int add(int []a) - ");
      int result = 0;
      for(int i = 0;i < a.length;i++)
         result += a[i];
      return result;
   }
}

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

초기화블럭  (0) 2011.01.22
생성자 . this() . this  (0) 2011.01.17
클래스메서드와 인스턴스메서드  (0) 2011.01.17
JVM 의 메모리구조  (0) 2011.01.16
메서드  (0) 2011.01.16


1.
class TestEx1 {
   int iv = 10;
   static int cv = 20;
   static void add() {
      System.out.println(cv);    // 클래스 변수이므로 사용가능
      // System.out.println(iv);     인스턴스 변수이므로 사용불가능
      TestEx1 t = new TestEx1(); // 객체생성
      System.out.println(t.iv);  // 사용가능
   }
}



2.
class TestEx1 {
   int iv = 10;
   static int cv = 20;
   static void abc() {}
   void add() {
      abc();
      System.out.println(cv);
      System.out.println(iv);
   }
}



3.
class MemberCall {
   int iv = 10;
   static int cv = 20;
   int iv2 = cv;
   // static int cv2 = iv;                 iv 는 인스턴스변수이므로 불가능
   static int cv2 = new MemberCall().iv;
   static void staticMethod1() {
      System.out.println(cv);
      // System.out.println(iv);       iv 는 인스턴스변수이므로 사용불가능
      MemberCall c = new MemberCall();
      System.out.println(c.iv);
   }
   void instanceMethod1() {
      System.out.println(cv);
      System.out.println(iv);
   }
   static void staticMethod2() {
      staticMethod1();              // static 메서드는 호출가능
      // instanceMethod1();         인스턴스메서드는 호출불가능
      MemberCall c = new MemberCall();
      c.instanceMethod1();
   }
   void instanceMethod2() {
      staticMethod1();
    instanceMethod1();
   }
   public static void main(String [] args) {
      staticMethod1(); // 같은클래스에 있는 메서드일때는 클래스이름을 제외한 메서드이름만 써도된다
      staticMethod2();

      MemberCall mc = new MemberCall();
      mc.instanceMethod1();
      mc.instanceMethod2();
   }
}

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

생성자 . this() . this  (0) 2011.01.17
메서드 오버로딩  (0) 2011.01.17
JVM 의 메모리구조  (0) 2011.01.16
메서드  (0) 2011.01.16
변수  (0) 2011.01.16



* 메서드영역 : 클래스정보와 클래스변수가 저장되는곳

* 호출스택 : 메서드의 작업공간. 메서드가 호출되면 메서드 수행에 필요한 메모리공간을 할당받고 메서드가
                 종료되면 사용하던 메모리를 반환한다


* 힙 : 인스턴스가 생성되는 공간. new 연산자에 의해서 생성되는 배열과 객체는 모두 여기에 생성된다




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

메서드 오버로딩  (0) 2011.01.17
클래스메서드와 인스턴스메서드  (0) 2011.01.17
메서드  (0) 2011.01.16
변수  (0) 2011.01.16
클래스와 객체  (0) 2011.01.13

1.
class Tv {
   String color;
   static int channel;
   void add() {
      System.out.println("메서드실행");
   }
}

class TvMain{
   public static void main(String[] args) {
      Tv t1 = new Tv();
      t1.add();
   }
}

메서드실행



2.
class Tv {
   String color;
   static int channel;
   void add(int a, int b) {
      System.out.println(a +" "+ b);
   }
}

class TvMain{
   public static void main(String[] args) {
      Tv t1 = new Tv();
      t1.add(100, 200);
   }
}

100 200



3.
class Tv {
   String color;
   static int channel;
   int add(int a, int b) {
      System.out.println(a+" "+b);
      return a + b;
   }
}

class TvMain{
   public static void main(String[] args) {
      Tv t1 = new Tv();
      int result = t1.add(100, 200);
      System.out.println(result);
   }
}

100 200
300



4.
class Tv {
   String color;
      static int channel;
      String add(int a, String s) {
      return a + s;
   }
}

class TvMain{
   public static void main(String[] args) {
      Tv t1 = new Tv();
      String result = t1.add(100, "str");
      System.out.println(result);
   }
}

100str



* return문 - 주의사항

   - 반환값이 있는 메서드는 모든 경우에 return문이 있어야 한다.
   - return문의 개수는 최소화하는 것이 좋다.



5.
class Data {
   int x;
}

class TvMain {
   public static void main(String[] args) {
      Data d = new Data();
      d.x = 10;
      System.out.println("main() : x = "+ d.x);
      change(d.x);
      System.out.println("After change(d.x)");
      System.out.println("main() : x = "+ d.x);
   }
   static void change(int x) {
      x = 1000;
      System.out.println("change() : x = "+ x);
   }
}

10
1000
10



6.
class Data {
   int x;
}

class TvMain {
   public static void main(String[] args) {
      Data d = new Data();
      d.x = 10;
      System.out.println("main() : x = "+ d.x);
      change(d);
      System.out.println("After change(d.x)");
      System.out.println("main() : x = "+ d.x);
   }
   static void change(Data a) {
      a.x = 1000;
      System.out.println("change() : x = "+ a.x);
   }
}

10
1000
1000

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

클래스메서드와 인스턴스메서드  (0) 2011.01.17
JVM 의 메모리구조  (0) 2011.01.16
변수  (0) 2011.01.16
클래스와 객체  (0) 2011.01.13
2차원 배열  (0) 2011.01.10


* 선언위치에 따른 변수




▶ 인스턴스변수(instance variable)
   - 각 인스턴스의 개별적인 저장공간. 인스턴스마다 다른 값 저장가능
   - 인스턴스 생성 후, ‘참조변수.인스턴스변수명’으로 접근
   - 인스턴스를 생성할 때 생성되고, 참조변수가 없을 때 가비지컬렉터에 의해자동제거됨

▶ 클래스변수(class variable)
   - 같은 클래스의 모든 인스턴스들이 공유하는 변수
   - 인스턴스 생성없이 ‘클래스이름.클래스변수명’으로 접근
   - 클래스가 로딩될 때 생성되고 프로그램이 종료될 때 소멸

▶ 지역변수(local variable)
   - 메서드 내에 선언되며, 메서드의 종료와 함께 소멸
   - 조건문, 반복문의 블럭{} 내에 선언된 지역변수는 블럭을 벗어나면 소멸



1.
class Tv {
   int a = channel;
   static int channel = 10;
}

정상실행
   static변수가 먼저 자리를 잡고 인스턴트 변수가 자리를 잡으므로



2.
class Tv {
   int a = 10;
   static int channel = a;
}

ERROR
   static변수가 먼저 자리를 잡으므로 a가 생성되기 전에 값을 넣어줄 수 없다



3.
class Card {
   String kind;
   int num;
   static int width;
   static int height;
}

class TvMain{
   public static void main(String[] args) {
      Card c1 = new Card();
      Card c2 = new Card();
      c1.kind = "heart";
      c1.num = 7;
      c2.kind = "spade";
      c2.num = 5;
      Card.width = 100;
      c1.height = 150;
      System.out.println(c1.kind +" "+ c1.num +" "+ c1.width +" "+ c1.height);
   }
}

heart 7 100 150

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

JVM 의 메모리구조  (0) 2011.01.16
메서드  (0) 2011.01.16
클래스와 객체  (0) 2011.01.13
2차원 배열  (0) 2011.01.10
문자열 배열  (0) 2011.01.10


* 클래스 : 객체를 생성
* 객체 : 변수와 메서드의 집합 (변수와 메서드를 멤버라 한다) 


1.
class Tv {
   String color = "black";  // 변수
   int channel = 5;
   boolean power = false;
   void power() {            // 메서드
      power = !power
   }
   void channelUp() {
      channel++;
   }
   void channelDown() {
      channel--;
   }
}

class TvMain{
   public static void main(String[] args) {
      Tv t;               // 객체선언
      t = new Tv();   // 객체생성
      System.out.println(t.channel);
      System.out.println(t.color);
      System.out.println(t.power);
      t.color = "red";
      t.channel++;
      t.power = true;
      System.out.println(t.channel);
      System.out.println(t.color);
      System.out.println(t.power);
   }
}

5
black
false
6
red
true




* 객체를 두개 만들고 대입할때




* 참조변수와 인스턴스의 관계



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

메서드  (0) 2011.01.16
변수  (0) 2011.01.16
2차원 배열  (0) 2011.01.10
문자열 배열  (0) 2011.01.10
버블정렬  (0) 2011.01.10


1.
class ObjArrayEx1 {
   public static void main(String[] args) {
      int [][]test = new int[2][3];
      test[0][0] = 100;
      test[0][1] = 200;
      test[0][2] = 300;
      test[1][0] = 500;
      test[1][1] = 600;
      test[1][2] = 700;
      int [][]a = {{100, 200, 300}, {400, 500, 600}};
      for(int i = 0;i < test.length;i++)
         for(int j = 0;j < test[i].length;j++)
            System.out.println("test["+ i +"]["+ j +"] = "+ test[i][j]);
   }
}


* 가변배열

2.
class ObjArrayEx1 {
   public static void main(String[] args) {
      int [][]test = new int[2][];
      test[0] = new int[3];
      test[1] = new int[2];
      test[0][0] = 100;
      test[0][1] = 200;
      test[0][2] = 300;
      test[1][0] = 500;
      test[1][1] = 600;
      int [][]a = {{10, 20, 30}, {50, 60}};
   }
}



3.
class ObjArrayEx1 {
   public static void main(String[] args) {
      char []abc = {'A', 'B', 'C', 'D'};
      char []number = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
      System.arraycopy(abc, 0, number, 0, abc.length);
      System.out.println(new String(number));
      System.arraycopy(abc, 0, number, 6, 3);
      System.out.println(new String(number));
   }
}

* abc 배열을 number 배열에 0번째부터 abc.length만큼 붙여넣겠다

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

변수  (0) 2011.01.16
클래스와 객체  (0) 2011.01.13
문자열 배열  (0) 2011.01.10
버블정렬  (0) 2011.01.10
Math.random  (0) 2011.01.10

+ Recent posts