(x,y)의 한 점을 표현하는 Point 클래스와 이를 상속받아 색을 가진 점을 표현하는 ColorPoint 클래스를 만들고 활용해보자.
package ch5;
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();
}
}
(1,2)
red(3,4)
클래스 Person을 아래와 같은 필드를 갖도록 선언하고, 클래스 Student는 Person을 상속받아 멤버 필드에 값을 저장하라.
private int weight;
int age;
protected int height;
public String name;
이 예제에서 Person 클래스의 private 필드인 weight는 Student 클래스에서는 접근이 불가능하여 슈퍼 클래스인 Person의 get, set 메소드를 통해서만 조작이 가능하다.
class Person {
private int weight;
int age;
protected int height;
public String name;
public void setWeight(int weight) {
this.weight = weight;
}
public int getWeight(int weight) {
return weight;
}
}
class Student extends Person {
public void set() {
age = 30;
name = "홍길동";
height = 175;
//weight=99;
setWeight(99);
}
}
public class InheritanceEx {
public static void main(String[] args) {
Student s = new Student();
s.set();
}
}
super()를 이용하여 ColorPoint 클래스의 생성자에서 슈퍼 클래스 Point의 생성자를 호출하는 예를 보인다.
class Point {
private int x,y;
public Point() {
this.x = 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 SuperEx {
public static void main(String[] args) {
ColorPoint cp = new ColorPoint(5,6,"blue");
cp.showColorPoint();
}
}
blue(5,6)
instanceof 연산자를 이용하여 상속 관계에 따라 레퍼런스가 가리키는 객체의 타입을 알아본다. 실행 결과는 무엇인가?
class Person {}
class Student extends Person{}
class Researcher extends Person {}
class Professor extends Person {}
public class InstanceOfEx {
static void print(Person p) {
if(p instanceof Person)
System.out.print("Person ");
if(p instanceof Student)
System.out.print("Student ");
if(p instanceof Researcher)
System.out.print("Researcher ");
if(p instanceof Professor)
System.out.print("Professor ");
System.out.println();
}
public static void main(String[] args) {
System.out.print("new Student() ->\t"); print(new Student());
System.out.print("new Researcher() ->\t"); print(new Researcher());
System.out.print("new Professor() ->\t"); print(new Professor());
}
}
new Student() -> Person Student
new Researcher() -> Person Researcher
new Professor() -> Person Professor
Shape의 draw() 메소드를 Line, Circle, Rect 클래스에서 목적에 맞게 오버라이딩하는 다형상의 사례를 보여준다.
class Shape {
public Shape next;
public Shape() {next = null;}
public void draw() {
System.out.println("Shape");
}
}
class Line extends Shape {
public void draw() {
System.out.println("Line");
}
}
class Rect extends Shape {
public void draw() {
System.out.println("Rect");
}
}
class Circle extends Shape {
public void draw() {
System.out.println("Circle");
}
}
public class MethodOverridingEx {
static void paint(Shape p) {
p.draw();
}
public static void main(String[] args) {
Line line = new Line();
paint(line);
paint(new Shape());
paint(new Line());
paint(new Rect());
paint(new Circle());
}
}
Line
Shape
Line
Rect
Circle
게임에서 무기를 표현하는 Weapon 클래스를 만들고 살상능력을 리턴하는 fire() 메소드를 작성하면 다음과 같다. fire()은 1을 리턴한다.
class Weapon {
protected int fire() {
return 1;
}
}
대포를 구현하기 위해 Weapon을 상속받는 Cannon 클래스를 작성하라. Cannon은 살상능력이 10이다. fire() 메소드를 이에 맞게 오버라이딩하라. main()을 작성하여 오버라이딩을 테스트하라.
class Cannon extends Weapon {
@Override
protected int fire() {
return 10;
}
}
public class Overriding {
public static void main(String[] args) {
Weapon weapon = new Weapon();
System.out.println("기본 무기의 살상 능력은 "+weapon.fire());
weapon = new Cannon();
System.out.println("대포의 살상 능력은 "+weapon.fire());
}
}
기본 무기의 살상 능력은 1
대포의 살상 능력은 10
다음 추상 클래스 Calculator를 상속받은 GoodCalc 클래스를 구현하라.
abstract class Calculator {
public abstract int add(int a, int b);
public abstract int subtract(int a, int b);
public abstract double average(int a[]);
}
추상 클래스인 Calculator는 add(), subtract(), average() 메소드를 추상 메소드로 선언하였을 뿐 어떻게 구현할지는 지시하지 않는다. 어떤 인자가 전달되고 어떤 타입의 값이 리턴되는지만 지정할 뿐이다. 구현은 서브 클래스의 몫이다. 다음과 같은 답을 만들어보았다.
public class GoodCalc extends Calculator {
@Override
public int add(int a, int b) {
return a+b;
}
@Override
public int subtract(int a, int b) {
return a-b;
}
@Override
public double average(int a[]) {
double sum=0;
for(int i=0; i<a.length; i++) {
sum += a[i];
}
return sum/a.length;
}
public static void main(String[] args) {
GoodCalc c = new GoodCalc();
System.out.println(c.add(2,3));
System.out.println(c.subtract(2,3));
System.out.println(c.average(new int [] {2,3,4}));
}
}
5
-1
3.0
PhoneInterface 인터페이스를 구현하고 flash() 메소드를 추가한 SamsungPhone 클래스를 작성하라.
interface PhoneInterface {
final int TIMEOUT = 10000;
void sendCall();
void receiveCall();
default void printLogo() {
System.out.println("** Phone **");
}
}
class SamsungPhone implements PhoneInterface {
@Override
public void sendCall() {
System.out.println("띠리리리링");
}
@Override
public void receiveCall() {
System.out.println("전화가 왔습니다.");
}
public void flash() {
System.out.println("전화기에 불이 켜졌습니다.");
}
}
public class InterfaceEx {
public static void main(String[] args) {
SamsungPhone phone = new SamsungPhone();
phone.printLogo();
phone.sendCall();
phone.receiveCall();
phone.flash();
}
}
** Phone **
띠리리리링
전화가 왔습니다.
전화기에 불이 켜졌습니다.
interface PhoneInterface {
final int TIMEOUT = 10000;
void sendCall();
void receiveCall();
default void printLogo() {
System.out.println("** Phone **");
}
}
interface MobilePhoneInterface extends PhoneInterface {
void sendSMS();
void receiveSMS();
}
interface MP3Interface {
public void play();
public void stop();
}
class PDA {
public int calculate(int x, int y) {
return x+y;
}
}
class SmartPhone extends PDA implements MobilePhoneInterface, MP3Interface {
@Override
public void sendCall() {
System.out.println("따르릉따르릉~");
}
@Override
public void receiveCall() {
System.out.println("전화가 왔습니다.");
}
@Override
public void sendSMS() {
System.out.println("문자갑니다.");
}
@Override
public void receiveSMS() {
System.out.println("문자가 왔습니다.");
}
@Override
public void play() {
System.out.println("음악을 재생합니다.");
}
@Override
public void stop() {
System.out.println("음악을 중단합니다.");
}
public void schedule() {
System.out.println("일정을 관리합니다.");
}
}
public class InterfaceEx {
public static void main(String[] args) {
SmartPhone phone = new SmartPhone();
phone.printLogo();
phone.sendCall();
phone.play();
System.out.println("3과 5를 더하면 "+phone.calculate(3,5));
phone.schedule();
}
}
** Phone **
따르릉따르릉~
음악을 재생합니다.
3과 5를 더하면 8
일정을 관리합니다.