///////
Search

08_클래스와객체(2)_조문주

생성자

인스턴스가 생성될 때 호출되는 인스턴스 초기화 메서드
생성자는 리턴 값이 없음
생성자의 이름과 클래스의 이름이 같아야 함
생성자는 초기화를 위한 데이터를 인수로 전달받을 수 있음
클래스 이름() {} // 매개 변수가 없는 생성자 선언 클래스 이름(인수 1, 인수 2){} // 매개 변수가 있는 생성자 선언 class Person{ Person (String name, int age){ } }
Java
복사
1.
생성자 호출시 연산자 new에 의해서 메모리에 Person 클래스의 인스턴스 생성
2.
호출된 생성자 Person() 수행됨
3.
연산자 new의 결과로 생성된 Person 인스턴스의 주소가 반환되어 참조 변수 person에 저장됨
Person person = new Person();
Java
복사

기본 생성자(default contrcutor)

클래스의 생성자를 정의하지 않았을 때 컴파일러가 자동으로 제공하는 생성자
기본 생성자는 매개 변수가 없음
특별히 인스턴스 초기화 작업이 요구되지 않는다면 생성자를 정의하지 않고 컴파일러가 제공하는 기본 생성자를 사용하는 것이 좋음
사용자가 미리 생성자를 만든 경우 컴파일러가 기본 생성자를 따로 만들지 않기 때문에 이때는 사용자가 기본 생성자를 생성해야 함

this

class Person{ String name; // 인스턴스 변수 String passport = "00000000"; Person (String name){ this.name = name; } }
Java
복사
this는 컴파일러에서 자동으로 생성
this는 인스턴스 자신을 가리키는 참조 변수
생성자의 매개변수로 선언된 변수의 이름이 인스턴스 변수와 같을 때 인스턴스 변수와 지역변수를 구분하기 위해 사용
this.name은 인스턴스 변수, name은 매개변수로 정의된 지역 변수

this()

class Person{ String name; String passport = "00000000"; public Person(String name) { this.name = name; } public Person(String name, String passport) { this(name); this.passport = passport; } }
Java
복사
같은 클래스의 다른 생성자를 호출할 때 사용
Person(String name, String passport) 생성자는 this()를 통해 Person(name) 생성자를 호출함

연습 문제

// main() 메서드를 실행했을 때 // "LG에서 만든 2017년형 32인치"와 같이 출력되는 클래스 생성 class TV{ String brand; int year; 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) { TV myTV = new TV("LG", 2017, 32); myTV.show(); } }
Java
복사
// 과목의 점수를 입력받아 Grade 객체 생성하고 평균 출력하기 import java.util.Scanner; class Grade{ int math; int science; int english; Grade(int math, int science, int english) { this.math = math; this.science = science; this.english = english; } public double average() { return (math + science + english)/3; } } public class GradeTest { public static void main(String[] args) { 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(); } }
Java
복사
노래 한 곡을 나타내는 Song 클래스를 작성하라. Song은 다음 필드로 구성된다.
노래의 제목을 나타내는 title
가수를 나타내는 artist
노래가 발표된 연도를 나타내는 year
국적을 나타내는 country
또한 Song 클래스에 다음 생성자와 메소드를 작성하라.
생성자 2개: 기본 생성자와 매개변수로 모든 필드를 초기화하는 생성자
노래 정보를 출력하는 show() 메소드
main() 메소드에서는 1978년, 스웨덴 국적의 ABBA가 부른 "Dancing Queen"을song 객체로 생성하고 show()를 이용하여 노래의 정보를 다음과 같이 출력하라.1978년 스웨덴국적의 ABBA가 부른 Dancing Queen
class Song { private String title; private String artist; private int year; private String country; Song() { this("title","artist",0000,"country"); } Song(String title, String artist, int year, String country) { this.title = title; this.artist = artist; this.year = year; this.country = country; } public void show() { System.out.println(year+"년 "+country+"국적의 "+artist+"가 부른 "+title); } } public class java_study4_3 { public static void main(String[] args) { // TODO Auto-generated method stub Song song = new Song("Dancing Queen","ABBA",1978,"스웨덴"); song.show(); } }
Java
복사