224p. 예제 7-1
class Tv {
boolean power;
int channel;
void power() { power = !power; }
void channelUp() { ++channel; }
void channelDown() { --channel; }
}
class SmartTv extends Tv { //부모 클래스(Tv)를 상속받음
boolean caption;
void displayCaption(String text) {
if (caption) {
System.out.println(text);
}
}
}
class Ex_JS {
public static void main(String args[]) {
SmartTv stv = new SmartTv(); //자손이 부모인 Tv클래스의 멤버를 사용할 수 있다.
stv.channel = 10;
stv.channelUp();
System.out.println(stv.channel);
stv.displayCaption("Hello, World");
stv.caption = true;
stv.displayCaption("Hello, World");
}
}
출력값:
11
Hello, World
232p. 예제 7-2
class Ex_JS {
public static void main(String args[]) {
Child c = new Child();
c.method();
}
}
class Parent { int x = 10; } //여기서 x는 super.x 이다.
class Child extends Parent { //Parent클래스를 상속 받음
int x = 20; //여기서 x는 this.x 이다.
void method( ) {
System.out.println("x=" + x); //가까운 x를 출력함
System.out.println("this.x=" + this.x);
System.out.println("super.x="+super.x);
}
}
232p. 예제 7-3
class Ex_JS {
public static void main(String args[]) {
Child2 c = new Child2();
c.method();
}
}
class Parent2 { int x = 10; } //여기서 x는 super.x, this.x 둘다 가능하다.
class Child2 extends Parent2 { //Parent클래스를 상속 받음
void method() {
System.out.println("x=" + x);
System.out.println("this.x=" + this.x);//어쨌든 x는 iv이므로
System.out.println("super.x="+super.x);//어쨌든 x는 조상의 것이므로
}
}
출력값:
x=10
this.x=10
super.x=10
233p. 예제 7-4
//조상의 생성자 super()
class Ex_JS {
public static void main(String args[]) {
Point3D p = new Point3D(1, 2, 3);
System.out.println("x=" + p.x + ",y=" + p.y+ ",z=" +p.z);
}
}
class Point {
int x, y;
Point(int x, int y) {//생성자 메서드, 인스턴스 변수 초기화
this.x = x;
this.y = y;
}
}
class Point3D extends Point { //Point클래스를 상속받음
int z;
Point3D(int x, int y, int z) { //Point3D 생성자 메서드
super(x, y); //super()를 통해 조상의 생성자를 호출
//모든 생성자는 반드시 첫줄에 다른 생성자를 호출해야됨
this.z = z; //자신의 멤버를 초기화
}
}
235p. 예제 7-5
//패키지 선언
package com.codechobo.book;
class Ex_JS {
public static void man(String[] args) {
System.out.println("Hello World!");
}
}
238p. 예제 7-6
//static import문
import static java.lang.System.out;
import static java.lang.Math.*;
class Ex_JS {
public static void main(String[] args) {
out.println(random());
out.println("Math.PI"+ PI);
}
}
출력값:
0.4160867747798218
Math.PI3.141592653589793
249p. 예제 7-7
class Ex_JS {
public static void main(String args[]) {
Car car = null;
FireEngine fe = new FireEngine();
FireEngine fe2 = null;
fe.water();
car = (Car)fe; //참조변수를 통해 형변환을 함, 조상타입 생략가능
//fe는 FireEngine객체를 가르킴> fe에 저장된 주소가 조상 Car의 참조변수인 car에 들어감
//car.water(); -> Car타입의 참조변수로는 water에 접근할 수 없으므로 에러가 뜸.
fe2 = (FireEngine)car;
//반대로 조상 참조변수 car에 저장된 주소를 자식 참조변수 fe2에 저장하기위해 형변환을 함(생략불가)
fe2.water();
}
}
class Car {
String colorString;
int door;
void drive( ) {
System.out.println("부릉부릉~");
}
void stop( ) {
System.out.println("멈춰!");
}
}
class FireEngine extends Car {
void water() {
System.out.println("물뿌리기!");
}
}
출력값:
물뿌리기!
물뿌리기!
253p. 예제 7-8
//매개변수의 다형성 예제
class Product { //제품
int price; //제품 가격
int bonusPoint; //제품 구매시 제공하는 보너스점수
Product(int price) {
this.price = price;
bonusPoint = (int)(price/10.0); //보너스점수는 제품 가격의 10%
}
}
class Tv1 extends Product {
Tv1(){
//조상클래스의 생성자 Product(int price) 호출
super(100); // Tv가격을 100만원으로 한다.
}
//Object클래스의 toString()을 오버라이딩한다.
public String toString() { return "Tv"; }
}
class Computer extends Product {
Computer() { super(200); }
public String toString() { return "Computer"; }
}
class Buyer { //고객
int money = 1000; //소유금액
int bonusPoint = 0; //보너스 점수
void buy(Product p) {
if(money < p.price) {
System.out.println("잔액이 부족하여 물건을 살 수 없습니다.");
return;
}
money -= p.price;
bonusPoint += p.bonusPoint;
System.out.println(p+"을/를 구입하셨습니다.");
}
}
class Ex_JS {
public static void main(String args[]) {
Buyer b = new Buyer(); //고객 인스턴스 생성
//Product p = new Tv1();
//b.buy(p); -> 두 줄을 간략화한것
b.buy(new Tv1()); //고객 클래스의 buy메서드 호출
b.buy(new Computer());
System.out.println("현재 남은 돈은 " + b.money + "만원입니다." );
System.out.println("현재 보너스점수는 " + b.bonusPoint + "점입니다.");
}
}
출력값:
Tv을/를 구입하셨습니다.
Computer을/를 구입하셨습니다.
현재 남은 돈은 700만원입니다.
현재 보너스점수는 30점입니다.
255p. 예제 7-9
//여러 종류의 객체를 배열로 다루기 예제
class Product2 { //제품
int price; //제품 가격
int bonusPoint; //제품 구매시 제공하는 보너스점수
Product2(int price) {
this.price = price;
bonusPoint = (int)(price/10.0); //보너스점수는 제품 가격의 10%
}
Product2() {}
}
class Tv2 extends Product2 {
Tv2(){ super(100); }
public String toString() { return "Tv"; }
}
class Computer2 extends Product2 {
Computer2() { super(200); }
public String toString() { return "Computer"; }
}
class Audio2 extends Product2 {
Audio2() { super(50); }
public String toString() { return "Audio"; }
}
class Buyer2 { //고객
int money = 1000; //소유금액
int bonusPoint = 0; //보너스 점수
Product2[] cart = new Product2[10]; //10칸짜리 장바구니
int i =0;
void buy(Product2 p) {
if(money < p.price) {
System.out.println("잔액이 부족하여 물건을 살 수 없습니다.");
return;
}
money -= p.price;
bonusPoint += p.bonusPoint;
cart[i++] = p; //cart[0]부터 순서대로 물품을 장바구니에 넣는다
System.out.println(p+"을/를 구입하셨습니다.");
}
void summary() {
int sum = 0;
String itemList ="";
for(int i=0; i<cart.length;i++) {
if(cart[i]==null) break;
sum += cart[i].price; //구매 물품의 금액 합계
itemList += cart[i] + ","; //구매 물품 목록
}
System.out.println("구입하신 물품의 총금액은 " + sum + "만원입니다.");
System.out.println("구입하신 제품은 " + itemList + "입니다.");
}
}
class Ex_JS {
public static void main(String args[]) {
Buyer2 b = new Buyer2(); //고객 인스턴스 생성
b.buy(new Tv2());
b.buy(new Computer2());
b.buy(new Audio2());
b.summary();
}
}
출력값:
Tv을/를 구입하셨습니다.
Computer을/를 구입하셨습니다.
Audio을/를 구입하셨습니다.
구입하신 물품의 총금액은 350만원입니다.
구입하신 제품은 Tv,Computer,Audio,입니다.