Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- ATMEGA128A
- hc-sr04
- java
- gpio
- soc 설계
- stop watch
- behavioral modeling
- Linked List
- ring counter
- pwm
- Algorithm
- prescaling
- BASYS3
- D Flip Flop
- Recursion
- test bench
- verilog
- LED
- Pspice
- atmega 128a
- DHT11
- FND
- dataflow modeling
- i2c 통신
- half adder
- uart 통신
- structural modeling
- Edge Detector
- KEYPAD
- vivado
Archives
- Today
- Total
거북이처럼 천천히
Java - 메서드와 생성자(2) 본문
생성자(constructor)
- 생성자는 new 명령으로 객체를 생성될 때, 호출 없이도 자동으로 실행된다. 주 목적은 객체의 데이터 필드의 값을 초기화하는 것이다.
- 생성자는 객체에게 필요한 초기화 작업을 하기에 적절한 장소이다.
생성자(constructor)의 형태
생성자는 메소드 형태를 가지고 있기 때문에 메소드이지만, 메소드의 일반적인 형태와는 조금의 차이점을 갖고 있다.
- 클래스명과 동일한 이름을 갖고 있다.
- 반환 타입이 존재하지 않는다. (리턴 값이 없어도 일반적인 메소드에서는 void 를 작성해야 한다.)
생성자(constructor) 활용
생성자를 활용 전에는 먼저, 객체를 생성하고, 참조 변수를 이용하여 변수에 접근하여 값을 대입하였다.
- Term2 term = new Term2();
- term.coef = 3;
- term.expo = 4;
public class Term2 {
public int coef;
public int expo;
public int calcTerm(int x) {
return (int) (coef*Math.pow(x, expo));
}
public void printTerm() {
System.out.printf("%dx^%d", coef, expo);
}
}
public class CalcuatePolynomialTerm {
public static void main(String[] args) {
Term2 term = new Term2();
term.coef = 3;
term.expo = 4;
}
}
하지만, 생성자를 활용하면 다음과 같이 객체 생성과 동시에 초기화를 한 번에 할 수 있다.
- Term2 term = new Term2(3, 4)
▶ 객체 생성과 동시에 변수(coef, expo)를 각각 3, 4로 초기화한다.
public class Term2 {
public int coef;
public int expo;
public Term2(int c, int e) {
coef = c;
expo = e;
}
public int calcTerm(int x) {
return (int) (coef*Math.pow(x, expo));
}
public void printTerm() {
System.out.printf("%dx^%d", coef, expo);
}
}
public class CalcuatePolynomialTerm {
public static void main(String[] args) {
Term2 term = new Term2(3, 4);
}
}
※ 단, 생성자가 반드시 매개 변수를 받을 필요가 없다. 매개 변수가 없는 생성자를 "Zero-parameter constructor"라고
한다.
※ 하나의 클래스는 여러 개의 생성자를 가질 수 있다.
▶ 생성자가 여러 개일 경우, 생성자마다 매개변수가 다르기 때문에 객체를 생성할 때, 어떤 인자를 전달하느냐에 따라
그에 해당하는 생성자가 동작한다.
this
this 키워드는 "객체, 자기자신"을 의미하며, 다음과 같은 경우에 사용된다.
- 클래스의 필드와 생성자/메서드의 매개변수 이름이 동일한 경우
- 클래스에 오버 로딩된 다른 생성자 호출
- 객체 자신의 참조값을 전달하고 싶을 때
메서드(method)와 생성자(constructor) 활용 예시 - 다항식 계산
import java.util.Scanner;
public class CalcutatePoly {
static Polynomial2[] poly = new Polynomial2[100];
static int nPoly = 0;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while(true) {
System.out.print("$ ");
String command = scan.next();
if(command.equalsIgnoreCase("create")) {
char name = scan.next().charAt(0);
int isContain = checkPolyName(name);
if(isContain!=-1)
System.out.println("This name of polynomial already exists.");
else {
poly[nPoly] = new Polynomial2(name);
nPoly++;
}
}else if(command.equalsIgnoreCase("add")) {
char name = scan.next().charAt(0);
int isContain = checkPolyName(name);
if(isContain==-1)
System.out.println("No such polynomial exists");
else {
int newCoef = scan.nextInt();
int newExpo = scan.nextInt();
poly[isContain].addTerm(newCoef, newExpo);
}
}else if(command.equalsIgnoreCase("calc")) {
char name = scan.next().charAt(0);
int isContain = checkPolyName(name);
if(isContain==-1)
System.out.println("No such polynomial exists");
else {
int value = scan.nextInt();
poly[isContain].calculatePoly(value);
}
}else if(command.equalsIgnoreCase("print")) {
char name = scan.next().charAt(0);
int isContain = checkPolyName(name);
if(isContain==-1)
System.out.println("No such polynomial exists");
else {
poly[isContain].printPoly();
}
}else if(command.equalsIgnoreCase("exit")) {
scan.close();
System.exit(0);
}else {
System.out.println("No such command exists.");
continue;
}
}
}
public static int checkPolyName(char name){
for(int i=0; i<nPoly; i++)
if(poly[i].name==name)
return i;
return -1;
}
}
public class Polynomial2 {
public int nTerm;
public Term2[] terms;
public char name;
public Polynomial2(char name) {
nTerm = 0;
terms = new Term2[100];
this.name = name;
}
// 항 추가
void addTerm(int newCoef, int newExpo) {
int idxTerm = -1;
for(int i=0; i<nTerm; i++)
if(terms[i].expo==newExpo&&idxTerm==-1)
idxTerm = i;
if(idxTerm == -1) {
int i = nTerm-1;
while(i>=0&&terms[i].expo<newExpo) {
terms[i+1]=terms[i];
i--;
}
terms[i+1] = new Term2(newCoef, newExpo);
nTerm++;
}else {
int sum = newCoef + terms[idxTerm].coef;
if(sum==0) {
for(int i=idxTerm+1; i<nTerm; i++)
terms[i-1] = terms[i];
nTerm--;
}
else
terms[idxTerm].coef = sum;
}
return;
}
// 다항식 계산
void calculatePoly(int value) {
int sum = 0;
for(int i=0; i<nTerm; i++)
sum += terms[i].calcTerm(value);
System.out.printf("Result of calculation is %d\n", sum);
return;
}
// 다항식 출력
void printPoly() {
System.out.printf("%c = ", name);
for(int i=0; i<nTerm; i++) {
if(i!=0) {
if(terms[i].coef>0)
System.out.print("+");
terms[i].printTerm();
}
else
terms[i].printTerm();
}
System.out.println();
}
}
public class Term2 {
public int coef;
public int expo;
public Term2(int c, int e) {
coef = c;
expo = e;
}
int calcTerm(int value) {
return (int) (coef*Math.pow(value, expo));
}
void printTerm() {
if(coef==1)
System.out.printf("x^%d", expo);
else if(coef==-1)
System.out.printf("-x^%d", expo);
else if(expo==0)
System.out.printf("%d", coef);
else if(expo==1)
System.out.printf("%dx", coef);
else if(expo==1&&coef==-1)
System.out.print("-x");
else if(expo==1&&coef==1)
System.out.print("x");
else
System.out.printf("%dx^%d", coef, expo);
}
}
'Back-end > Java 개념' 카테고리의 다른 글
Java - 클래스 정리 (4) (0) | 2022.06.27 |
---|---|
Java - 클래스 정리 (3) (0) | 2022.06.27 |
Java - 클래스 정리 (2) (0) | 2022.06.26 |
Java - 클래스 정리 (1) (0) | 2022.06.26 |
Java - 변수 선언 위치에 따른 변수 구분 (0) | 2022.06.26 |