쇼핑몰의 판매 상품을 만들어보자.
Book
, Album
, Movie
3가지 상품을 클래스로 만들어야 한다.Item
이라는 이름을 사용하면 된다.name
, price
Book
: 저자(author
), isbn(isbn
)Album
: 아티스트(artist
)Movie
: 감독(director
), 배우(actor
)package extends1.ex;
public class ShopMain {
public static void main(String[] args) {
Book book = new Book("JAVA", 10000, "han", "12345");
Album album = new Album("앨범1", 15000, "seo");
Movie movie = new Movie("영화1", 18000, "감독1", "배우1");
book.print();
album.print();
movie.print();
int sum = book.getPrice() + album.getPrice() + movie.getPrice();
System.out.println("상품 가격의 합: " + sum);
}
}
단축키
Override Methods → ⌃ + O
package extends1.ex;
public class Item {
private String name;
private int price;
public Item(String name, int price) {
this.name = name;
this.price = price;
}
public int getPrice() {
return price;
}
// ex) 이름: JAVA, 가격: 10000
public void print() {
System.out.println("이름: " + name + ", 가격: " + price);
}
}
package extends1.ex;
public class Book extends Item {
private String author;
private String isbn;
public Book(String name, int price, String author, String isbn) {
super(name, price);
this.author = author;
this.isbn = isbn;
}
@Override
public void print() {
super.print();
System.out.println("- 저자: " + author + ", isbn: " + isbn);
}
}
package extends1.ex;
public class Album extends Item {
private String artist;
public Album(String name, int price, String artist) {
super(name, price);
this.artist = artist;
}
@Override
public void print() {
super.print();
System.out.println("- 아티스트: " + artist);
}
}
package extends1.ex;
public class Movie extends Item {
private String director;
private String actor;
public Movie(String name, int price, String director, String actor) {
super(name, price);
this.director = director;
this.actor = actor;
}
@Override
public void print() {
super.print();
System.out.println("- 감독: " + director + ", 배우: " + actor);
}
}