kingsubin

5. 클래스 본문

Java

5. 클래스

kingsubin 2020. 12. 19. 00:05

목표

자바의 Class에 대해 학습하세요.

학습할 것 (필수)

  • 클래스 정의하는 방법
  • 객체 만드는 방법 (new 키워드 이해하기)
  • 메소드 정의하는 방법
  • 생성자 정의하는 방법
  • this 키워드 이해하기

과제 (Optional)

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

1. 클래스 정의하는 방법

Class

클래스는 객체가 생성되는 사용자 정의 청사진 또는 프로토 타입입니다.

한 유형의 모든 개체에 공통적인 속성 또는 메서드 집합을 나타냅니다.

일반적으로 클래스 선언에는 이러한 요소들을 순서대로 포함합니다.

 

1. Modifiers: A class can be public or has default access.

1) private (accessible within the class where defined)

2) default or pakage private (when no access specifier is specified)

3) protected

4) public (accessible from any class)

 

2. class keyword: class keyword is used to create a class.

3. Class name: The name should begin with a initial letter (capitalized by convention).

4. Superclass (if any): The name of the class'parent (superclass), if any, preceded by the keyword extends.

  A class can only extend (subclass) one parent.

5. Interfaces (if any): A comma-seprarated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.

6. Body: The class body surrounded by braces, { }.

 

Constructors are used for initializing new objects. Fields are variables that provides tha state of the class and its objects, and methods are used to implement the behavior of the class and its objects.

// Class Declaration
public class Dog {

    //Instance Variables
    String anme;
    String breed;
    int age;
    String color;
}

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

Object

It is a basic unit of Object Oriented Programming and represents the real life entities.

A typical Java program creates many objects, which as you know, interact by invoking methods.

An object consists of:

1. State: It is represented by attributes of an object. It also reflects the properties of an object.

2. Behavior: It is represented by methods of an object. It also reflects the response of an object with other objects.

3: Identity: It gives a unique name to an object and enables one object to interact with other objects.

 

The new operator instanitates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the class constructor.

The Java compiler differentiates the constructors based on the number and the type of the arguments.

All classes have at least one constructor. If a class does not explictily declare any, the Java compiler automatically provides a no-argument constructor, also called the default constructor.

Dog tuffy = new Dog("tuffy", "papillon", 5, "white");

 

ways to create objects in Java

Test t = new Test();
// consider class Test present in com.p1 package
Test obj = (Test)Class.forName("com.p1.Test").newInstance();
Test t1 = new Test();

// creating clone of above object
Test t2 = (Test)t1.clone();

 

Creating multiple objects by one type only (A good practice)

in real-time, we need different objects of a class in different methods.

Creating a number of references for storing them is not a good practice and therefore we declare a static reference variable and us it whenever required. In this case, wastage of memory is less. The objects that are not referenced anymore will be destroyed by Garbage Collector of java.

Test test = new Test();
test = new Test();

3. 메소드 정의하는 방법

Method Declaration

In general, method declarations has six components :

 

1. Modifier: Defines access type of the method i.e. from where it can be accessed in your application.

In Java, there 4 type of the access specifiers.

1-1) public: accessible in all class in your application.

1-2) protected: accessible within the class in which it is defined and in its subclass

1-3) private: accessible only within the class in which it is defined.

1-4) default (declared/defined without using any modifier): accessible within same class and pacakage within which its class is defined.

 

2. The return type: The data type of the value returned by the method or void if does not return a value.

3. Method Name: the rules for field names apply to method names as well, but the convention is a little different.

4. Parameter list: Comma separated list of the input parameters are defined, preceded with their data type, within the enclosed parenthesis. If there are no parameters, you must use empty parentheses ().

5. Exception list: The exceptions you expect by the method can throw, you can specify these exception.

6. Method body: it is enclosed between braces. The code you need to be executed to perform your intended operations.

https://www.geeksforgeeks.org/methods-in-java/

 

// Method
public void eat(String food) {
    System.out.println(food + " : eat !");
}

4. 생성자 정의하는 방법

Constructors are used to initialize the object's state. Like methods, a constructor also contains collection of statements that are exectued at time of Object creation.

 

Need of Constructor

constructors are used to assign values to the class variables at the time of object creation, either explicitly done by the programmer or by Java itself (default constructor).

 

When is a Constructor called ?

Each time an object is created using new() keyword at least one constructor is invoked to assign initial values to the data members of the same class.

 

Rules for writing Constructor

  • Constructor of a class must have same name as the class name in which it resides.
  • A constructor in Java can not be abstract, final, static ans Synchronized.
  • Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor.

 

class Geek {
    // No-argument constructor
    Geek() {
        System.out.println("Constructor called");
    }
}
class Geek {
    String name;
    int id;
    
    // Parameterized Constructor
    Geek(String name, int id) {
        this.name = name;
        this.id = id;
    }
}

5. this 키워드 이해하기

'this' is a reference variable that refers to the current object.

 

1. Using 'this' keyword to refer current class instance variables.

class Test {
    int a;
    int b;
    
    Test(int a, int b) {
        this.a = a;
        this.b = b;
    }
}

 

2. Using this() to invoke current class constructor

class Test {
    int a;
    int b;
    
    Test() {
        this(10, 20);
    }
}

 

3. Using 'this' keyword to return the current class instance

class Test {
    int a;
    int b;
    
    Test get() {
        return this;
    }
}

 

4. Using 'this' keyword as method parameter

class Test {
    int a;
    int b;
    
    void display(Test obj) {
        System.out.println("a = " + obj.a + ", b = " + obj.b);
    }
    
    void get() {
        display(this);
    }
}

 

5. Using 'this' keyword to invoke current class method

class Test {
    void display() { 
        this.show(); 
        System.out.println("Inside display function"); 
    } 
      
    void show() { 
        System.out.println("Inside show funcion"); 
    }
    
    public static void main(String args[]) { 
        Test t1 = new Test(); 
        t1.display(); 
    } 
}

// Inside show funcion
// Inside display function

 

6. Using 'this' keyword as an argument in the constructor call

class A {
    B obj;
    
    A(B obj) {
        this.obj = obj;
        obj.display();
    }
}

class B {
    int x = 5;
    
    B() {
        A obj = new A(this);
    }
    
    void display() {
        System.out.println("Value of x in Class B : " + x);
    }
    
    public static void main(String[] args) {
        B obj = new B();
    }
}

// Value of x in Class B : 5

과제

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

 

 

kingsubin.tistory.com/111?category=911807

 

트리 정리

트리 (tree) 자료구조의 일종 사이클이 없는 연결 그래프 정점의 개수 : V 간선의 개수 : V-1 정점 V, 간선 V 개 라면 사이클이 1개 있다. 정점 V, 간선 V-1 개라면 트리라 할 수 있을까 ? 아니다. 왜냐면

kingsubin.tistory.com

 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public class BinaryTree {
    Node root;
 
    public BinaryTree(Node root) {
        this.root = root;
    }
 
    void bfs(Node node) {
        if (root == null) {
            System.out.println("Empty Tree");
        }
        Queue<Node> q = new LinkedList<>();
        q.offer(root);
        while (!q.isEmpty()) {
            Node cur = q.poll();
            System.out.print(cur.value);
            if (cur.left != null) {
                q.offer(cur.left);
            }
            if (cur.right != null) {
                q.offer(cur.right);
            }
        }
    }
 
    void dfs(Node node) {
        inorder(node);
    }
 
    void inorder(Node node) {
        if (node == nullreturn;
        inorder(node.left);
        System.out.print(node.value);
        inorder(node.right);
    }
}
 
class Node {
    int value;
    Node left;
    Node right;
 
    public Node(int value) {
        this.value = value;
    }
 
    public Node(int value, Node left, Node right) {
        this.value = value;
        this.left = left;
        this.right = right;
    }
}
 
cs

 

\

이 트리 구조로 DFS, BFS 테스트

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@DisplayName("이진트리 테스트")
class BinaryTreeTests {
    static BinaryTree binaryTree;
    static Node root;
 
    @BeforeEach
    void setup() {
        Node node9 = new Node(9nullnull);
        Node node8 = new Node(8nullnull);
        Node node7 = new Node(7nullnull);
        Node node6 = new Node(6null, node9);
        Node node5 = new Node(5, node7, node8);
        Node node4 = new Node(4nullnull);
        Node node3 = new Node(3null, node6);
        Node node2 = new Node(2, node4, node5);
        root = new Node(1, node2, node3);
        binaryTree = new BinaryTree(root);
    }
 
    @Test
    void BFS() {
        binaryTree.bfs(root);
    }
 
    @Test
    void DFS() {
        binaryTree.dfs(root);
    }
}
cs

 

테스트 출력

 

 


※ 출처

www.geeksforgeeks.org/java/?ref=leftbar

 

※ 스터디

github.com/whiteship/live-study/issues/5

'Java' 카테고리의 다른 글

7. 패키지  (0) 2021.01.02
6. 상속  (0) 2020.12.23
4. 제어문  (0) 2020.12.04
3. 연산자  (0) 2020.11.28
2. 자바 데이터 타입, 변수 그리고 배열  (0) 2020.11.25
0 Comments
댓글쓰기 폼