Ex01_interface
package com.mywork.ex;
interface Animal{
void move();
default void eat(String food) {
System.out.println(food + " 먹는다.");
}
}
class Dog implements Animal{
@Override
public void move() {
System.out.println("개가 달린다.");
}
}
public class Ex01_interface {
public static void main(String[] args) {
Animal animal = new Dog();
animal.eat("개밥");
animal.move();
}
}
Ex02_interface
package com.mywork.ex;
interface Shape{
double PI = 3.141592;
double calcArea();
void output();
}
class Rect implements Shape{
private int width;
private int height;
public Rect(int width, int height) {
this.width = width;
this.height = height;
}
@Override
public double calcArea() {
return width * height;
}
@Override
public void output() {
System.out.println("너비 : " + width);
System.out.println("높이 : " + height);
System.out.println("크기 : " + calcArea());
}
}
class Circle implements Shape{
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calcArea() {
return PI * Math.pow(radius, 2);
}
@Override
public void output() {
System.out.println("반지름 : " + radius);
System.out.println("크기 : " + calcArea());
}
}
public class Ex02_interface {
public static void main(String[] args) {
Shape[] arr = new Shape[2];
arr[0] = new Rect(2, 3);
arr[0].output();
arr[1] = new Circle(1.5);
arr[1].output();
}
}
Ex03_interface
package com.mywork.ex;
interface Eatable {
void eat();
}
class My{
public void dirty() {
System.out.println("내껀 더럽지.");
}
}
class Apple extends My implements Eatable{
@Override
public void eat() {
System.out.println("사과는 아침에 먹는 게 좋다.");
}
}
class Banana extends My implements Eatable{
@Override
public void eat() {
System.out.println("바나나는 껍질은 드시지 마세요.");
}
}
class Computer extends My{
}
public class Ex03_interface {
public static void main(String[] args) {
My[] list = new My[3];
list[0] = new Apple();
list[1] = new Banana();
list[2] = new Computer();
for(int i = 0; i < list.length; i++) {
list[i].dirty();
if(list[i] instanceof Eatable) {
((Eatable)list[i]).eat();
}
}
}
}