[스터디할래 05] 클래스

이 글은 ‘백기선’ 개발자님과 함께하는 온라인 자바 스터디에 참여하여 준비/학습한 내용을 정리하는 글입니다.📚

정리는 ‘Java in a nutshell’를 기반으로 하였습니다.

클래스

클래스는 자바의 근본 구조 요소이다. 클래스 없이는 자바 프로그램을 작성할 수 없다.

Class

Object

클래스 정의하는 방법

keyword class class_name (extends) {
	// class members
}

필드와 메소드

클래스의 멤버({} 안에 있는 요소들)는 크게 4가지로 나뉜다.

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

생성자 정의하는 방법

생성자는 다음 조건을 만족해야 한다.

this 키워드 이해하기


Optional 과제

int 값을 가지고 있는 이진 트리를 나타내는 Node 라는 클래스를 정의하세요.(int value, Node left, right를 가지고 있어야 합니다.)

public class Node {

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

	Node(int value) {
		this.value = value;
	}
	
	public int getValue() {
		return this.value;
	}

	public int setValue(int value) {
		return this.value = value;
	}

	public Node getLeft() {
		return this.left;
	}

	public void setLeft(Node left) {
		this.left = left;
	}

	public Node getRight() {
		return this.right;
	}

	public void setRight(Node right) {
		this.right = right;
	}

}

BinrayTree라는 클래스를 정의하고 주어진 노드를 기준으로 출력하는 bfs(Node node)dfs(Node node) 메소드를 구현하세요.(DFS는 왼쪽, 루트, 오른쪽 순으로 순회하세요.)

class BinaryTree {

	private Node root;

	BinaryTree(Node root) {
		this.root = root;
	}

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

		while (!queue.isEmpty()) {
			Node currentNode = queue.poll();
			System.out.println(currentNode.getValue());
			if (Objects.nonNull(currentNode.getLeft())) {
				queue.add(currentNode.getLeft());
			}
			if (Objects.nonNull(currentNode.getRight())) {
				queue.add(currentNode.getRight());
			}
		}
	}

	public void dfs() {
		visitInorder(root);
	}

	public void visitInorder(Node node) {
		if (Objects.nonNull(node.getLeft())) {
			visitInorder(node.getLeft());
		}
		System.out.println(node.getValue());
		if (Objects.nonNull(node.getRight())) {
			visitInorder(node.getRight());
		}
	}

}