티스토리 뷰

JAVA

Constructor in Java

seoca 2019. 1. 2. 09:32


Constructor 


1. A constructor has no return value, not even void. Constructor actually initializes the object of the class. If there is a return value, it would create an unexpected object. 

첫번째, 생성자는 반환형이 선언되어 있지도, 반환형이 있지도 않다.


2. the Constructor name is the same as the class name. 

두번째, 클래스의 이름과 동일하다.


3. the constructor can be overloaded

여러개의 생성자가 존재할 수 있다.

 

4. if there is no constructor, a default constructor will be created.

사용자가 생성자를 만들지 않으면 디폴트생성자가 자동으로 생성된다.




The purpose of Constructor 


To initialize the object of the class. Constructors can receive values just like any other methods.

생성자를 이용하면, 초기화를 한결 수월하게 해준다. 




example code

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
import java.util.*;
//import-> 다른 패키지의 클래스를 사용하고자 할 때 명시.
import java.lang.*;
import java.io.*
//* -> 앞과 같은 이름의 package로 묶여있는 class의 instance생성에는 
//package 이름은 생략하고 class의 이름만 명시하겠다는 의미
 
class Calculator{
    int left, right;
        public Calculator(left, right){
            this.left=left;
            this.right=right;
        }
        public void sub(){
            System.out,println(this.left-this.right);
        }
        public void addition(){
            System.out,println(this.left+this.right);
        }
}
 
class demo{
    public static void main (String[] arg){
         Calculator c1 = new.Calculator(20,30); //생성자를 이용 한결 간단한 초기화가 가능하다.
        c1.sub();
        c1.addition();
    }
}
cs





reference

https://opentutorials.org/course/1223/5519

'JAVA' 카테고리의 다른 글

super keyword  (0) 2019.01.03
Inheritance  (0) 2019.01.03
Nested if-else example  (0) 2019.01.02
instance in Java  (0) 2018.12.31
main method in Java  (0) 2018.12.31