P.330 문제 5번

스크린샷 2022-01-22 오후 11.03.25.png

Parent.java

Parent.java

Chlid.java

Chlid.java

public class Parent {
    public String nation;

    public Parent() {
        this("대한민국");
        System.out.println("Parent() call");
    }

    public Parent(String nation) {
        this.nation = nation;
        System.out.println("Parent(String nation) call");
    }
}
public class Child extends Parent {
    private String name;

    public Child() {
        this("홍길동");
        System.out.println("Child() call");
    }

    public Child(String name) {
        this.name = name;
        System.out.println("Child(String name) call");
    }
}

ChlidExample.java

ChlidExample.java

결과

결과

public class ChildExample {
    public static void main(String[] args) {
        Child child = new Child();
    }
}

설명

  1. Child의 생성자 Child()는 부모 클래스인 Parent의 기본 생성자 Parent()를 먼저 호출한다. 여기에서 ‘this("대한민국")’이 ‘Parent(String nation)’생성자를 실행시킨다 → Parent(String nation) call
  2. 호출 후 기본 생성자 ‘Parent()’를 출력시키고 종료된다 → Parent() call
  3. Child클래스도 부모클래스와 동일하게 먼저 ‘this("홍길동");’이 ‘Child(String name)’를 실행시킨다 → Child(String name) call
  4. 호출 후 기본 생성자 ‘Child()’를 출력시킨다 → Child() call

Product

public class Product {
	private String name;
	
	public Product(String name) {
		this.name = name;
	}
	public double getPrice() {
		return 0.0;
	}
	public String getName() {
		return name;
	}
}
public class NoteBook extends Product{
	public NoteBook(String name) {
		super(name);
	}
	public double getPrice() {
		return 2500.0;
	}
}
public class SmartPhone extends Product {
	private boolean apple = false;

	public SmartPhone(String name) {
		super(name);
		if (getName().startsWith("Apple")) {
			apple = true;
		}
	}

	public double getPrice() {
		if (apple) {
			return 1500.0;
		} else {
			return 1000.0;
		}
	}

	public String getPlatform() {
		if (apple) {
			return "Apple";
		} else {
			return "Android";
		}
	}
}
public class Cart {
	private Product[] products = new Product[3];
	
	public void addProduct(Product p) {
		for (int i = 0; i < products.length; i++) {
			if (products[i] == null) {
				products[i] = p;
				break;
			}
		}
	}
	
	public Product[] getProducts() {
		return products;
	}
	public String getDetails() {
		StringBuilder sb = new StringBuilder();
		for(Product p : products) {
			sb.append("Name: ");
			sb.append(p.getName());
			sb.append("\\nPrice: ");
			sb.append(p.getPrice());
			if(p instanceof SmartPhone) {
				SmartPhone s = (SmartPhone)p;
				sb.append("\\nPlatform: ");
				sb.append(s.getPlatform());
			}
			sb.append("\\n-------------------\\n");
		}
		return sb.toString();
	}
}
public class CartTest {
	public static void main(String[] args) {
		Cart cart = new Cart();
		cart.addProduct(new NoteBook("ThinkPad"));
		cart.addProduct(new SmartPhone("Samsung Galuxy"));
		cart.addProduct(new SmartPhone("Apple Iphone"));
		
		System.out.println(cart.getProducts().length);
		System.out.println(cart.getDetails());
	}
}

객체지향 프로그래밍이란?