목표
  • 자바의 Class에 대해 학습하세요.
학습할 것 (필수)
  • 클래스 정의하는 방법
  • 객체 만드는 방법 (new 키워드 이해하기)
  • 메소드 정의하는 방법
  • 생성자 정의하는 방법
  • this 키워드 이해하기
과제 (Optional)
  • int 값을 가지고 있는 이진 트리를 나타내는 Node 라는 클래스를 정의하세요.
  • int value, Node left, right를 가지고 있어야 합니다.
  • BinrayTree라는 클래스를 정의하고 주어진 노드를 기준으로 출력하는 bfs(Node node)와 dfs(Node node) 메소드를 구현하세요.
  • DFS는 왼쪽, 루트, 오른쪽 순으로 순회하세요.

클래스 정의하는 방법

자바에서 클래스(class)란 객체를 정의하는 틀 또는 설계도라고 합니다. 자바에서는 이러한 설계도인 클래스(class)를 가지고 여러 객체를 생성하여 사용하게 됩니다. 클래스는 객체의 상태를 나타내느 필드(field)와 객체의 행위를 나태는 메서드(method)로 구성됩니다.

필드

객체지향 개념에서 속성에 해당하는 것으로 멤버 변수라고도 합니다. 구조는 다음과 같습니다.

private String name; 한정자 / 자료형 / 변수명

메서드

객체지향 개념에서 행위에 해당하는 것으로, 클래스를 사용하여 실행하는 동작입니다. 구조는 다음과 같습니다.

// 한정자 / 리턴값 / 함수명(매개변수 ,,,)
public int add(int a, int b) { 
  return a + b;
}

객체 만드는 방법 (new 키워드 이해하기)

클래스를 이용하여 객체를 생성 하게 되는데, 객체를 new 키워드로 할당하게 되면 인스턴스가 생성되어 집니다. 인스턴스가 생성될 때에는 메모리에 올라간 상태입니다.

객체(인스턴스) 생성 방법
// 클래스 / 참조변수 / 생성자
Student student = new Student(); 

생성자는 클래스나 인스턴스를 생성할 때 호출하는 특수한 목적의 메서드입니다. 일반적으로 변수를 초기화하거나 필요한 다른 개체를 생성하는 작업을 처리합니다. new 키워드를 사용하여 객체를 생성하는 시점에 호출되며, 클래스는 하나 이상의 생성자를 가질 수 있습니다.

생성자 예제
public class People {
  private String name;
  private int age;

  public Student() { // 기본생성자
    name = "이름없음";
    age = 0;
  }

  public People(String name, int age) { // 파라미터가 있는 생성자
    this.name = name;
    this.age = age;
    }
  }

public class Main {
  public static void main(String[] args) {
    Student student = new Student();
    System.out.println("이름 : " + student.getName()); // 이름없음
    System.out.println("나이 : " + student.getAge());    // 0

    Student a = new Student("둘리", 18);
    System.out.println("이름 : " + a.getName());          // 둘리 
    System.out.println("나이 : " + a.getAge());             // 18
  }
}

메소드 정의하는 방법 (메서드 오버로딩, 오버라이딩)

메서드 오버로딩

메서드 이름을 동일하지만 파라미터가 다른 여러 메서드를 만드는 것을 말합니다.

메서드 오버로딩 예제
public class Calculator {
  public int sum(int num1, int num2) {
    return num1 + num2;
  }

  public int sum(int num1, int num2, num3) {
    return num1 + num2 + num3;
  }
}

메서드 오버라이딩

메서드 오버라이딩은 상위 클래스에서 정의한 메서드를 서브 클래스에서 재정의하는 것을 말합니다.

class Gun {
  public void shot() {
    System.out.println("탕");
  }
}

class Ak47 extends Gun {
  @Override
  public void shot() {
    System.out.println("두두두두두두두두둗두두두두둗ㄷ");
  }
}

public class Test {
  public static void main(String[] args) {
    Gun gun = new Gun();
    Ak47 ak47 = new Ak47();

    gun.shot(); // 탕
    ak47.shot(); // 두두두두두두두두둗두두두두둗ㄷ
  }
}

this 키워드

자바에서(Java) this는 '객체, 자기 자신'을 나타냅니다.

특징

  1. this는 생성자와도 같이 사용할 수 있습니다. 자기 자신의 생성자를 호출할 때 사용됩니다.
  2. this는 객체 자신을 가리키는 키워드입니다. 이를 이용하여 자기 자신의 레퍼런스를 반환할 수 있습니다.
  3. this 키워드는 실행 중에 즉, 동적으로 자기 자신 객체에 대한 레퍼런스라고 정의됩니다. 따라서 정적(static) 메서드에서는 사용할 수 없습니다.

과제 (Optional)

  • int 값을 가지고 있는 이진 트리를 나타내는 Node 라는 클래스를 정의하세요.
  • int value, Node left, right를 가지고 있어야 합니다.
  • BinrayTree라는 클래스를 정의하고 주어진 노드를 기준으로 출력하는 bfs(Node node)와 dfs(Node node) 메소드를 구현하세요.
  • DFS는 왼쪽, 루트, 오른쪽 순으로 순회하세요.
Node.java
public class Node {

    private int value;
    private Node left;
    private Node right;

    public Node(int value) {
        this.value = value;
        this.left = null;
        this.right = null;
    }

    public Node(int value, Node left, Node right) {
        this.value = value;
        this.left = left;
        this.right = right;
    }

    public int getValue() {
        return value;
    }

    public Node getLeft() {
        return left;
    }

    public Node getRight() {
        return right;
    }
}
BinrayTree.java
public class BinrayTree {

    private Node root;

    public BinrayTree(Node root) {
        this.root = root;
    }

    public void bfs() {
        Queue<Node> q = new LinkedList<>();
        q.add(root);

        while(!q.isEmpty()) {
            int size = q.size();
            for (int i = 0; i < size; i++) {
                Node cur = q.poll();
                System.out.print(cur.getValue() + " ");
                if (cur.getLeft() != null) q.offer(cur.getLeft());
                if (cur.getRight() != null) q.offer(cur.getRight());
            }
        }
    }

    // 왼쪽, 루트, 오른쪽 순
    public void dfs() {
        dfs(root);
    }

    private void dfs(Node node) {
        if (node == null) {
            return;
        }

        dfs(node.getLeft());
        System.out.print(node.getValue() + " ");
        dfs(node.getRight());
    }
}
BinrayTreeTest.java
class BinrayTreeTest {

    BinrayTree binrayTree;

    @BeforeEach
    void before() {
        Node node4 = new Node(4);
        Node node5 = new Node(5);
        Node node2 = new Node(2, node4, node5);
        Node node3 = new Node(3);
        Node root = new Node(1, node2, node3);
        binrayTree = new BinrayTree(root);
        /*
             1
            / \
           2   3
          / \
         4   5
         */
    }

    @Test
    void test() {
        System.out.print("BFS : ");
        binrayTree.bfs();
        System.out.println();
        System.out.print("DFS : ");
        binrayTree.dfs();

        // BFS : 1 2 3 4 5
        // DFS : 4 2 5 1 3
    }
}
참조

+ 따끈한 최근 게시물