Parent.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
결과
public class ChildExample {
public static void main(String[] args) {
Child child = new Child();
}
}
설명
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());
}
}