명품자바프로그래밍 Chapter5_Lab04
+ 교재 외 실습
1|고객 클래스 만들기(Person.java,Customer.java)
- 재정의 연습예제
public class Person {
private String name; //이름 속성
private String address; //주소 속성
private String phone; //전화번호 속성 //일반 01012345678형태가 int의 범위 밖이라는 오류! -> String으로 함
public Person(String name, String address, String phone) { //생성자
this.name = name;
this.address = address;
this.phone = phone;
}
public String getName() { // 각 필드에 대하여 접근자와 설정자 메소드 작성 (Source -> Generates Getters and Setters)
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
public class Customer extends Person {
private int c_num; //고객번호 속성
private int mile; //마일리지 속성
public Customer(String name, String address, String phone, int c_num, int mile) { //생성자1
super(name, address, phone); //부모생성자 호출
this.c_num = c_num;
this.mile = mile;
}
public Customer(int c_num,int mile) { //생성자2
super("안현주", "서울시" , "01012345678" ); //부모클래스가 가지고 있는 생성자의 형식에 따라서 명시적인 호출을 한다.
this.c_num = c_num;
this.mile = mile;
}
public int getC_num() { // 각 필드에 대하여 접근자와 설정자 메소드 작성 (Source -> Generates Getters and Setters)
return c_num;
}
public void setC_num(int c_num) {
this.c_num = c_num;
}
public int getMile() {
return mile;
}
public void setMile(int mile) {
this.mile = mile;
}
}
2| Magazine 클래스 만들기 (Book1.java,Magazine.java)
- 재정의 연습예제
public class Book1 {
private String tittle; //제목 속성
private int page_num; //페이지 수 속성
private String author; //저자 속성
static int count; //count는 클래스 변수로 선언
public Book1(String tittle, int page_num, String author) { //생성자
this.tittle = tittle;
this.page_num = page_num;
this.author = author;
}
public String getTittle() { // 각 필드에 대하여 접근자와 설정자 메소드 작성 (Source -> Generates Getters and Setters)
return tittle;
}
public void setTittle(String tittle) {
this.tittle = tittle;
}
public int getPage_num() {
return page_num;
}
public void setPage_num(int page_num) {
this.page_num = page_num;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public static int getCount() { //책의 개수에 대해서는 접근자 메소드만 클래스 메소드로 작성
return count;
}
}
public class Magazine extends Book1 { //Book1의 하위 클래스
private int release_info; //발매일 정보 속성
public Magazine(String tittle, int page_num, String author, int release_info) { //생성자1
super(tittle, page_num, author); //부모 생성자 호출
this.release_info = release_info;
}
public Magazine(int release_info) { //생성자2
super("어린왕자", 32, "생텍쥐페리"); //부모클래스가 가지고 있는 생성자의 형식에 따라서 명시적인 호출을 한다.
this.release_info = release_info;
}
public int getRelease_info() { // 각 필드에 대하여 접근자와 설정자 메소드 작성 (Source -> Generates Getters and Setters)
return release_info;
}
public void setRelease_info(int release_info) {
this.release_info = release_info;
}
}
3| 학생 만들기 (Human.java, Student.java, StudentTest.java)
- 재정의 연습예제
public class Human {
private String name; //이름 속성
private int age; //나이 속성
public Human(String name, int age) { //생성자 , 매개변수로 이름과 나이 받기
this.name = name; //매개 변수의 값으로 필드를 초기화
this.age = age;
}
public String getName() { //각 필드에 대하여 접근자와 변경자 메소드를 작성
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override // toString()작성 (Object 클래스의 toString() 메소드 재정의) //Source 메뉴 활용
public String toString() {
return "이름 : " + name + ", 나이 : " + age ; //객체의 현재값들을 문자열로 반환
}
}
public class Student extends Human{
private String major; //전공 속성
private int sID; //학번 속성
public Student(String name, int age, String major, int sID) { //생성자 (매개변수로 이름,나이 전공, 학번을 받아와서 초기화)
super(name, age); //부모클래스의 생성자 호출(이름,나이)
this.major = major; //매개변수로 받아온 값으로 멤버 변수의 전공과 학번을 초기화
this.sID = sID;
}
public String getMajor() { //필드(전공)에 대하여 접근자와 변경자 메소드를 작성
return major;
}
public void setMajor(String major) {
this.major = major;
}
@Override //toString() 작성 (Object 클래스의 toString() 메소드 재정의)
public String toString() { //부모의 toSTring()을 호출받아 받아온 문자열 값에 추가로 전공 값 연결하여 문자열 반환
return "[학생 정보]" + super.toString() + ", 전공 : " + major + ", 학번 : " + sID + "]";
}
}
import java.util.Scanner;
public class StudentTest {
public static void main(String[] args) {
Human h[] = new Human[3]; //크기 3의 Human 객체 배열 생성
Student s[] = new Student[3]; //크기 3의 Student 객체 배열 생성
Scanner scan = new Scanner(System.in);
String x,a;
int y,b;
for(int i=0;i<h.length;i++) { //human 객체 배열의 크기만큼 반복문 시행
System.out.print("[" + (i+1) + "] " + "Human 입력: ");
x = scan.next(); //String형의 name
y = scan.nextInt(); //int형의 age
h[i] = new Human(x,y);
}
for(int j=0;j<s.length;j++) { //student 객체 배열의 크기만큼 반복문 시행
System.out.print("[" + (j+1) + "] " + "Student 입력: ");
x = scan.next(); //String형의 name
y = scan.nextInt(); //int형의 age
a = scan.next(); //전공은 문자열이므로 String 변수인 x사용
b = scan.nextInt(); //int형의 학번
s[j] = new Student(x,y,a,b);
}
for (int i=0; i<h.length;i++) { //객체참조 변수 이름으로 출력문 작성
System.out.println(h[i]);
}
for (int j=0; j<s.length;j++) { //객체참조 변수 이름으로 출력문 작성
System.out.println(s[j]);
}
scan.close();
}
}
4| Item.java, Fooe.java, Book.java, Movie.java, Buyer.java, Test.java
- 재정의 연습 예제
public class Item {
String name; //이름 속성
int price; //가격 속성
public Item(String name, int price) { //생성자
this.name = name;
this.price = price;
}
}
public class Food extends Item{
public Food(String name, int price) { //생성자 , 이름과 가격을 매개변수로!
super(name, price);
}
@Override
public String toString() {
return "[Food]" + super.name ;
}
}
public class Book extends Item{
String author; //저자 속성
public Book(String name,int price, String author) { //이름, 가격, 저자를 매개변수로 받아서 설정
super(name, price);
this.author = author;
}
@Override
public String toString() {
return "[Book]" + super.name + ", 저자:" + this.author ;
}
}
public class Movie extends Item{
String director; //감독 속성
public Movie( String name,int price, String director) { //생성자 매개변수 3개
super( name, price);
this.director = director;
}
@Override
public String toString() {
return "[Movie]" + super.name + ", 감독:" + director;
}
}
public class Buyer {
int money; //money 속성
//money를 매개변수로 받아서 멤버 변수 설정
public Buyer(int money) { //생성자
this.money = money;
}
void buy(Item t, int n) { //Buy 메소드
System.out.println(t.toString() + "=>" + n + "개 구매" ); //기본으로 나와야하는 출력문
if (money < t.price*n) { //기본 설정된 money보다 물품을 구매한 총 가격이 더 크면 잔액이 부족하다는 경고문 출력
System.out.println("잔액부족: " + money);
}
else { //잔액이 충분할 경우 money에서 구매한 가격만큼 빼주고 출력한다.
this.money -= t.price*n;
System.out.println("구매 완료 후 잔액 : " + money);
}
}
}
public class Test {
public static void main(String args[]) {
Buyer m = new Buyer(40000);
m.buy((new Food("비빔밥",5000)),3);
m.buy((new Food("라면",3000)),2);
m.buy((new Book("Java Programming",7000, "자바")),1);
m.buy((new Movie("부산행",8000, "연상호")),1);
m.buy((new Food("김밥",2000)),3);
}
}
실습 13,14| 추상 클래스 실습- 도형 구성 묘사 (Shape.java, Circle.java, Oval.java, Rect.java, Shapes.java)
interface Shape {// 추상 클래스
final double PI =3.14;
void draw(); // 도형을 그리는 추상 메소드
double getArea(); // 도형의 면적을 리턴하는 추상 메소드
default public void redraw() { //디폴트 메소드
System.out.print("--- 다시 그립니다.");
draw();
}
}
class Circle implements Shape {//인터페이스 구현
private int radius; // 반지름
public Circle(int radius) {
this.radius = radius;
}
@Override //오버라이딩 출력문
public void draw() {
System.out.println("반지름이 " + radius + "인 원입니다.");
}
@Override //오버라이딩 면적
public double getArea() {
return PI*radius*radius;
}
}
class Oval implements Shape {//인터페이스 구현
private int rec1,rec2; //
public Oval(int rec1, int rec2) { //생성자
this.rec1 = rec1;
this.rec2 = rec2;
}
@Override //오버라이딩 출력문
public void draw() {
System.out.println("너비: " + rec1 + ", 높이 :" + rec2 + "에 내접하는 타원입니다.");
}
@Override //오버라이딩 : 면적
public double getArea() {
return PI*(rec1/2)*(rec2/2);
}
}
class Rect implements Shape {//인터페이스 구현
private int rect1,rect2; //
public Rect(int rect1, int rect2) { //생성자
this.rect1 = rect1;
this.rect2 = rect2;
}
@Override //오버라이딩 : 출력문
public void draw() {
System.out.println("너비: " + rect1 + ", 높이 :" + rect2 + "의 사각형입니다.");
}
@Override //오버라이딩 : 면적
public double getArea() {
return rect1*rect2;
}
}
public class Shapes {
static public void main(String [] args) {
Shape [] list = new Shape[3]; //Shape을 상속받은 클래스 객체의 레퍼런스 배열
list[0] = new Circle(10); //반지름이 10인 원 객체
list[1] = new Oval(20,30); //20x30 사각형에 내접하는 타원
list[2] = new Rect(10,40); //10x40 크기의 사각형
for(int i=0; i<list.length; i++)
list[i].redraw();
for(int i=0; i<list.length; i++)
System.out.println("면적은"+list[i].getArea());
}
}
'Programming > JAVA' 카테고리의 다른 글
제너릭과 컬렉션 (0) | 2020.10.16 |
---|---|
패키지 개념과 자바 기본 패키지 (0) | 2020.10.16 |
클래스와 객체 (0) | 2020.10.16 |
반복문과 배열 그리고 예외 처리 (0) | 2020.09.08 |
[Java] print, printf, println의 차이 (0) | 2020.09.03 |
댓글