class Point {
    private int x, y;

    public void set(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public void showPoint() {
        System.out.println("(" + x + "," + y+")");
    }
}
class ColorPoint extends Point {
    private String color;

    public void setColor(String color) {
        this.color = color;
    }

    public void showColorPoint() {
        System.out.print(color);
        showPoint();
    }
}
public class ColorPointEx {
    public static void main(String[] args) {
        Point p = new Point();
        p.set(1, 2);
        p.showPoint();

        ColorPoint cp = new ColorPoint();
        cp.set(3, 4);
        cp.setColor("red");
        cp.showColorPoint();
    }
}

super() 사용 예제로 클래스 변환

class Point {
    private int x, y;

    public Point() {
        this.x = 0;
        this.y = 0;
    }

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public void showPoint() {
        System.out.println("(" + x + "," + y + ")");
    }
}
class ColorPoint extends Point {
    private String color;

    public ColorPoint(int x, int y, String color) {
        super(x,y);
        this.color = color;
    }

    public void showColorPoint() {
        System.out.print(color);
        showPoint();
    }
}
public class ColorPointEx {
    public static void main(String[] args) {
        ColorPoint cp = new ColorPoint(5, 6, "blue");
        cp.showColorPoint();
    }
}

업캐스트

class Person {
    String name;
    String id;

    public Person(String name) {
        this.name = name;
    }
}

class Student extends Person {
    String grade;
    String department;

    public Student(String name) {
        super(name);
    }
}

public class UpcastingEx {
    public static void main(String[] args) {
        Person p;
        Student s = new Student("이재문");
        p = s;
        System.out.println(p.name);

        p.grade = "A"; // 컴파일 오류
        p.department = "Com"; // 컴파일 오류

        s.grade = "";
        s.department = "";
    }
}

다운캐스팅

public class DowncastingEx {
    public static void main(String[] args) {
        Person p = new Student("이재문");
        Student s;

        s = (Student) p;

        System.out.println(s.name);
        s.grade = "A";

				Person p1 = new Person("홍길동");
        Student s2 = (Student) p1;
        s2.id = "aaa";
        s2.grade = "B";
    }
}

209-212 업캐스팅 예제 문제