생성자란?
인스턴스가 생성될 때마다 호출되는 ‘인스턴스(객체) 초기화 메서드’
iv 초기화란?
편리하게 초기화 하기 위해서 생성하는 것
기본생성자란?
매개변수가 없는 생성자
생성자가 하나도 없을때만, 컴파일러가 자동 추가
기본생성자는 항상 만들어준다! (원칙)
클래스이름() {}
Point(){} // piont 클래스의 기본 생성자 이 코드를 자동으로 추가해줌 하나도 없을 때만
HTML
복사
class BankAccount {
int balance;
public BankAccount() { // 컴파일러에 의해 자동 삽입되는 '디폴트 생성자’
// empty
}
public int deposit(int amount) {...}
public int withdraw(int amount) {...}
public int checkMyBalance() {...}
}
HTML
복사
this 함수
생성자 this()
생성자에서 다른 생성자 호출할 때 사용
같은 클래스 내에서 생성자를 호출 할 때 this 사용 // 이는 규칙임
또한 호출은 첫 줄에서만 호출 가능
클래스 이름 대신 this 사용
코드의 중복을 제거하기 위해서
참조변수 this
생성자 this 와 전혀 관계없음
인스턴스 자신을 가리키는 참조변수
인스턴스 메서드(생성자포함) 에서 사용가능
지역변수 lv 인스턴스변수 iv 구별할 때 사용
this 는 객체 자신을 의미 따라서 iv lv 구분이 안가는 경우에는 this 를 붙여서 구분한다
클래스 메서드 경우 iv 사용할 수 없기 때문에 this 또한 사용 불가함
문제
1.
자바 클래스를 작성하는 연습을 해보자. 다음 main 메소드를 실행하였을때 예시와 같이 출력되도록 TV 클래스를 작성하라.
public static void main(String[] args) {
TV myTV = new TV("LG", 2017, 32); //LG에서 만든 2017년 32인치
myTV.show();
}
LG에서 만든 2017년형 32인치 TV
Java
복사
풀이
class TV {
private String brand;
private int year;
private int inch;
TV(String brand, int year, int inch) {
this.brand = brand;
this.year = year;
this.inch = inch;
}
public void show() {
System.out.println(brand+"에서 만든 "+year+"년형 "+inch+"인치 TV");
}
}
public class TVTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
TV myTV = new TV("LG", 2017, 32);
myTV.show();
}
}
HTML
복사
2.
Grade 클래스를 작성해보자. 3 과목의 점수를 입력받아 Grade 객체를 생성하고 성적 평균을 출력하는 main() 실행 예시는 다음과 같음
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.print("수학, 과학, 영어 순으로 3개의 정수 입력 >> ");
int math = sc.nextInt();
int science = sc.nextInt();
int english = sc.nextInt();
Grade me = new Grade(math, science, english);
System.out.println("평균은 "+me.average()); // average()는 평균을 계산하여 리턴
sc.close();
}
/*
출력은 수학, 과학, 영어 순으로 3개의 정수 입력 -> 90 88 96
평균은 91
*/
HTML
복사
풀이
import java.util.Scanner;
class Grade {
private int math;
private int science;
private int english;
Grade(int math, int science, int english) {
this.math = math;
this.science = science;
this.english = english;
}
public int average() {
return (math + science + english) / 3;
}
}
public class GradeTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.print("수학, 과학, 영어 순으로 3개의 정수 입력 >> ");
int math = sc.nextInt();
int science = sc.nextInt();
int english = sc.nextInt();
Grade me = new Grade(math, science, english);
System.out.println("평균은 "+me.average());
sc.close();
}
}
HTML
복사