-
목표
자바의 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.
// 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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253public 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 == null) return;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 \
1234567891011121314151617181920212223242526272829@DisplayName("이진트리 테스트")class BinaryTreeTests {static BinaryTree binaryTree;static Node root;@BeforeEachvoid setup() {Node node9 = new Node(9, null, null);Node node8 = new Node(8, null, null);Node node7 = new Node(7, null, null);Node node6 = new Node(6, null, node9);Node node5 = new Node(5, node7, node8);Node node4 = new Node(4, null, null);Node node3 = new Node(3, null, node6);Node node2 = new Node(2, node4, node5);root = new Node(1, node2, node3);binaryTree = new BinaryTree(root);}@Testvoid BFS() {binaryTree.bfs(root);}@Testvoid DFS() {binaryTree.dfs(root);}}cs
※ 출처
www.geeksforgeeks.org/java/?ref=leftbar
※ 스터디