01. 복잡한 상속 계층 구조 프로그램
º 하나의 부모 클래스와 하나의 자식 클래스만으로 이루어진 계층 구조가 일반적이지만 복잡한 상속 계층 구조를 생성할 수도 있습니다. 자식 클래스가 다른 클래스의 부모 클래스가 될 수도 있습니다. 예를 들어 Shape이 Rectangle의 부모 클래스이고 다시 Rectangle이 ColoredRectangle의 부모 클래스라고 할 때 각 클래스의 생성자가 호출되는 프로그램을 작성하시오.
<1-1> Shape 클래스
public class Shape {
private int x;
private int y;
public Shape(int x, int y) {
System.out.println("Shape()");
this.x = x;
this.y = y;
}
}
<1-2> Rectangle 클래스
public class Rectangle extends Shape {
private int width;
private int height;
public Rectangle(int x, int y, int width, int height) {
super(x, y);
System.out.println("Rectangle()");
this.width = width;
this.height = height;
}
double calArea() {
return width * height;
}
}
<1-3> ColoredRectangle 클래스
public class ColoredRectangle extends Rectangle {
String color;
public ColoredRectangle(int x, int y, int width, int height, String color) {
super(x, y, width, height);
System.out.println("ColoredRectangle()");
this.color = color;
}
public static void main(String[] args) {
ColoredRectangle obj = new ColoredRectangle(10,20,20,20,"red");
}
}
02. instanceof 연산자 활용
º instanceof 연산자를 이용하여 상속 관계에 따라 레퍼런스가 가리키는 객체의 타입을 알아보시오.
<2-1> InstanceOf 클래스
class Person1{}
class Student1 extends Person1{}
class Researcher1 extends Person1{}
class Professor1 extends Researcher1{}
public class InstanceOf {
static void print(Person1 p) {
if(p instanceof Person1) {
System.out.print("Person1 ");
}
if(p instanceof Stuent1) {
System.out.print("Student1 ");
}
if(p instanceof Researcher1) {
System.out.print("Researcher1 ");
}
if(p instanceof Professor1) {
System.out.print("Professor1 ");
}
System.out.println();
}
}
<2-2> InstanceOfEx 클래스
public class InstanceOfEx {
public static void main(String[] args) {
System.out.print("new Student1() -> \t");
InstanceOf.print(new Student1());
System.out.print("new Researcher1() -> \t");
InstanceOf.print(new Researcher1());
System.out.print("new Professor1() -> \t");
InstanceOf.print(new Professor1());
}
}
03. 메소드 오버라이딩
º Calculator 클래스, Computer 클래스를 생성하고 Calculator의 자식 클래스인 Computer에서 원의 넓이를 구하는 Calculator의 areaCircle()를 사용하지 않고 메소드 재정의 하시오.
<3-1> 슈퍼클래스(Calculator)
public class Calculator {
double areaCircle(double r) {
System.out.println("Calculator의 areaCircle()!");
return 3.14159 * r * r;
}
}
<3-2> 서브클래스(Computer)
public class Computer extends Calculator {
@Override
double areaCircle(double r) {
System.out.println("Computer의 areaCircle()!!");
return Math.PI * r * r;
}
}
<3-3> 실행클래스(ComputerEx)
public class ComputerEx {
public static void main(String[] args) {
int r = 10;
Calculator calculator = new Calculator();
System.out.println("원의면적: " + calculator.areaCircle(r));
System.out.println();
Computer computer = new Computer();
System.out.println("원의면적: " + computer.areaCircle(r));
}
}
04. 부모 메소드 호출 : super 사용
º 클래스 Supersonic는 클래스 Airplane를 상속한다.
- 클래스 Airplane의 fly()는 일반 비행 모드이지만 클래스 Supersonic의 fly()는 초음속 비행 모드와 일반 비행 모드 두 가지로 동작한다.
- 비행모드가 SUPERSONIC 상수값을 가질 경우는 "초음속비행"을 출력하지만 그렇지 않은 경우 Airplane fly() 메소드를 호출한다.
- main()에서 클래스 Supersonic의 객체를 생성하고 변수 값을 적절하게 대입한 후 출력해 보시오.
<4-1> 부모클래스 (Airplane)
public class Airplane {
public void land() {
System.out.println("착륙!");
}
public voidfly() {
System.out.println("비행!!");
}
public void takeoff() {
System.out.println("이륙!!!");
}
}
<4-2> 자식클래스 (Supersonic)
public class Supersonic extends Airplane {
public static final int NORMAL = 1;
public static final int SUPERSONIC = 2;
public int flyMode = NORMAL;
@Override
public void fly() {
if(flyMode == SUPERSONIC) {
System.out.println("초음속비행!!!!");
}else {
super.fly();
}
}
}
<4-3> 실행클래스 (SupersonicEx)
public class SupersonicEx {
public static void main(String[] args) {
Supersonic sa = new Supersonic();
sa.takeoff();
sa.fly();
sa.flyMode = Supersonic.SUPERSONIC;
sa.fly();
sa.flyMode = Supersonic.NORMAL;
sa.fly();
sa.land();
}
}
05. 추상 클래스
º Phone 클래스를 추상 클래스로 선언하고 객체를 생성할 수 없음을 보이시오.
또한 SmartPhone 자식 클래스로 객체를 생성하여 추상 클래스의 메소드 사용을 보이시오.
- 추상 클래스 선언은 abstract 키워드 사용
- 추상 클래스는 new 연산자를 이용해서 객체를 만들 수 없음
- 상속을 통해 자식 클래스만 만들 수 있음
<5-1> 추상클래스(Phone)
public abstract class Phone {
//필드
public String owner; //소유자
//생성자
public Phone(String owner) {
this.owner = owner;
}
//메소드
public void turnOn() {
System.out.println("전원 On!");
}]
public void turnOff() {
System.out.println("전원 Off!");
}
}
<5-2> 실체클래스(SmartPhone)
public class SmartPhone extends Phone {
//생성자
public SmartPhone(String owner) {
super(owner);
}
//메소드
public void Search() {
System.out.println("Internet 검색!!!");
}
}
<5-3> 실행클래스(PhoneEx)
public class PhoneEx {
public static void main(String[] args) {
//Phone phone = new Phone();
SmartPhone = smartPhone = new SmartPhone("김이화");
smartPhone.turnOn();
smartPhone.Search();
smartPhone.turnOff();
}
}
06. 추상 메소드
º Animal 클래스를 추상 클래스로 선언하고 sound() 메소드를 추상 메소드로 선언해 보시오.
- 메소드의 선언만 통일하고, 실행 내용은 실체 클래스마다 달라야 하는 경우 사용
<6-1> 추상클래스(Animal)
public abstract class Animal { //추상 클래스
public String kind;
public void live() {
System.out.println("호흡!");
}
public abstract void sound(); //추상 메소드
}
<6-2> 실체클래스(Dog)
public class Dog extends Animal {
public Dog() {
this.kind = "포유류";
}
@Override
public void sound() {
System.out.println("멍멍");
}
}
<6-3> 실체클래스(Cat)
public class Cat extends Animal {
public Cat() {
this.kind = "포유류";
}
@Override
public void sound() {
System.out.println("야옹");
}
}
<6-4> 실행클래스(AnimalEx)
public class AnimalEx {
public static void main(String[] args) {
Dog dog = new Dog();
Cat cat = new Cat();
dog.sound();
cat.sound();
System.out.println("======");
Animal animal = null;
animal = new Dog();
animal.sound();
animal = new Cat();
animal.sound();
System.out.println("======");
}
}
07. Interface 구현
º PhoneInterface 인터페이스를 구현하고 flash() 메소드를 추가한 SamsungPhone 클래스를 작성하시오.
<7-1> Interface 선언(Phoneinterface)
public interface PhoneInterface {
final int TIMEOUT = 10000; //상수 필드 선언
void sendCall(); //추상 메소드
void receiveCall(); //추상 메소드
default void printLogo() { //default 메소드
System.out.println("** Phone! **);
}
}
<7-2> Interface 구현(SamsungPhone)
public class SamsungPhone implements PhoneInterface { //인터페이스 구현
//PhoneInterface의 모든 추상 메소드 구현
@Override
public void sendCall() {
System.out.println("따르릉");
}
@Override
public void receiveCall() {
System.out.println("전화 왔습니다!");
}
//메소드 추가 작성
public void flash() {
System.out.println("전화기에 불이 켜졌네요!");
}
}
<7-3> Interface 실행 클래스(InterfaceEx)
public class InterfaceEx {
public static void main(String[] args) {
SamsungPhone phone = new SamsungPhone();
phone.printLogo();
phone.sendCall();
phone.receiveCall();
phone.flash();
}
}
08. 클래스 상속과 함께 Interface 구현
º 클래스의 상속과 함께 Interface를 구현하시오.
<8-1> 클래스 작성(PDA)
public class PDA {
public int calculate(int x, int y) {
return x+y;
}
}
<8-2> Interface 구현(SamsungPhone)
public class SamsungPhone extends PDA implements PhoneInterface { //인터페이스 구현
//PhoneInterface의 모든 추상 메소드 구현
@OVerride
public void sendCall() {
System.out.println("따르릉");
}
@Override
public void receiveCall() {
System.out.println("전화 왔습니다!");
}
//메소드 추가 작성
public void flash() {
System.out.println("전화기에 불이 켜졌네요!!");
}
public void schedule() {
System.out.println("일정 관리!!!");
}
}
<8-3> Interface 실행 클래스(InterfaceEx)
public class InterfaceEx {
public static void main(String[] args) {
SamsungPhone phone = new SamsungPhone();
phone.printLogo();
phone.sendCall();
phone.receiveCall();
phone.flash();
System.out.println("2+5 = " + phone.calculate(2, 5));
phone.schedule();
}
}
'JAVA > 자바 실습' 카테고리의 다른 글
Java | Lab11 (0) | 2021.06.09 |
---|---|
Java | Lab10 (0) | 2021.06.09 |
Java | Lab8 (0) | 2021.06.08 |
Java | Lab6 (0) | 2021.04.16 |
Java | Lab5 (0) | 2021.04.15 |