본문 바로가기

Java

05.03 인터페이스

 

 

인터페이스와추상클래스차이.hwp
0.03MB
workspace.zip
15.61MB

 

 

 

추상클래스는 인스턴스 멤버 가질 수 있다. 필드 필요시 인터페이스말고 추상클래스 사용,접근제한자 사용가능

인터페이스는 가질 수 없다. 공통적인 규격 정하는 역할만 한다. 접근제한자 public으로 고정, 상수는 사용가능

default 메소드 : 몸통만 있는 메소드 . 필요한 사람만 재정의해서 사용할 수 있게 정의해놓은 것.

 

 

인터페이스 객체는 다중구현이 가능하다. 인터페이스 여러개를 구현하고 있어도 재정의 하기 때문에 다중구현이 가능.

기본적인 구성멤버 : 필드는 상수 /  메소드는 추상메소드

 

인터페이스는 생성자 x , 필드 정의시 무조건 초기화되어있어야함.


package a_base;

 

public class AirRemoteControl implements RemoteControl {

 

private int temperature = 24; // 온도

 

 

@Override

public void turnOn() {

System.out.println("에어컨을 켭니다.");

}

 

@Override

public void turnOff() {

System.out.println("에어컨을 끕니다.");

}

 

@Override

public void setValue(int value) {

if(this.temperature >= MAX_VALUE && this.temperature <=MIN_VALUE) {

return;

}

this.temperature = value;

System.out.println(this.temperature+"로 온도를 설정합니다.");

}

 

}

 


package a_base;

 

public interface RemoteControl {

 

public static final int MAX_VALUE = 30;

// 컴파일 시 public static final 자동 생성

int MIN_VALUE = 0;

 

public abstract void turnOn();

// public abstract 자동생성

void turnOff();

 

void setValue(int value);

// void setValue(int value) {} 사용불가

}


package a_base;

 

public class RemoteControlExam {

 

public static void main(String[] args) {

//클래스를 통해 직접접근가능.

System.out.println(RemoteControl.MAX_VALUE);

System.out.println(RemoteControl.MIN_VALUE);

//값 변경 불가(상수)

// RemoteControl.MIN_VALUE=100;

//인터페이스로 객체 생성 불가

// RemoteControl tvRemote = new RemoteControl();

 

//인터페이스의 다형성

RemoteControl tvRemote; // = new RemoteControl();

tvRemote = new TVRemoteControl();

tvRemote.turnOn();

tvRemote.setValue(11);

tvRemote.turnOff();

 

RemoteControl airControl = new AirRemoteControl();

airControl.turnOn();

airControl.setValue(18);

airControl.turnOff();

 

RemoteControl smartTvRemote = new SmartTVRemoteControl();

smartTvRemote.turnOn();

smartTvRemote.setValue(300);

smartTvRemote.turnOff();

//RemoteControl 기능만 사용가능

// smartTvRemote.search("가디언즈 오브 갤럭시 VOL.3");

 

Searchable searchRemote = (Searchable)smartTvRemote;

searchRemote.search("가디언즈 오브 갤럭시 VOL.3");

 

if(smartTvRemote instanceof SmartTVRemoteControl) {

SmartTVRemoteControl strc = (SmartTVRemoteControl)smartTvRemote;

strc.turnOn();

strc.search("슬램덩크");

strc.turnOff();

}

}

}


package a_base;

 

public interface Searchable {

int MAX_VALUE = 500;

int MIN_VALUE = 1;

 

void search(String word);

}


 

package a_base;

 

public class SmartTVRemoteControl implements RemoteControl, Searchable {

 

int channel = 1;

 

@Override

public void turnOn() {

System.out.println("스마트 TV를 켭니다.");

}

 

@Override

public void turnOff() {

System.out.println("스마트 TV를 끕니다.");

}

 

@Override

public void setValue(int value) {

//인터페이스간 필드 중복 시 사용법

if(channel >= Searchable.MAX_VALUE && channel <= Searchable.MIN_VALUE) {

System.out.println("변경할 수 없는 채널입니다.");

return;

}

this.channel = value;

System.out.println(this.channel+"로 채널을 변경합니다.");

}

 

//검색 기능

@Override

public void search(String word) {

System.out.println(word+"로 채널을 검색합니다.");

}

 

}


 

package a_base;

 

public class TVRemoteControl implements RemoteControl{

 

int volume = 1;

 

 

 

@Override

public void turnOn() {

System.out.println("TV를 켭니다.");

}

 

@Override

public void turnOff() {

System.out.println("TV를 끕니다.");

}

 

@Override

public void setValue(int value) {

//인터페이스를 구현하고 있는 객체는 인터페이스가 가지고 있는 필드에 직접적으로 접근 가능.

if(value <= MAX_VALUE && value >= MIN_VALUE) {

this.volume = value;

System.out.println(volume+"로 음량을 설정합니다.");

}else {

System.out.println("변경할 수 없습니다.");

}

}

 

}


 


package b_dafault;

 

public interface Printable {

void print();

 

default void colorPrint() {

System.out.println("컬러 프린트 기능이 없습니다.");

}

}


 

package b_dafault;

 

public class LGPrinter implements Printable{

 

@Override

public void print() {

System.out.println("LGPrinter가 출력합니다.");

}

 

@Override

public void colorPrint() {

System.out.println("LG 프린터기가 컬러로 출력합니다.");

}

 

}


 

package b_dafault;

 

public class HPPrinter implements Printable{

 

@Override

public void print() {

System.out.println("HPPrinter 가 출력합니다.");

}

 

}


 

package b_dafault;

 

public class Window {

 

public void print(Printable printer) {

printer.print();

printer.colorPrint();

}

 

public static void main(String[] args) {

Window window = new Window();

Printable lg = new LGPrinter();

window.print(lg);

Printable hp = new HPPrinter();

window.print(hp);

}

}



 

package c_extends;

 

public interface A {

void methodA();

 

default void methodB() {

System.out.println("A interface의 methodB");

}

//정적 멤버기 때문에 접근 방식이 틀려서 상속관계에서 중복이라도 충돌x

static void methodC() {

System.out.println("A interface의 methodC");

}

}

 

interface B {

void methodB();

}

 

interface C extends A,B{

void methodC();

//default와 추상메소드 중복인 경우 default로 만들어줘야함.

public default void methodB() {

System.out.println("C interface의 method B");

}

 

 

 

 

}


 

package c_extends;

 

public class MyClass implements C{

 

@Override

public void methodA() {

System.out.println("myClass methodA");

}

 

/*

@Override

public void methodB() {

System.out.println("myClass methodB");

}

*/

 

@Override

public void methodC() {

System.out.println("myClass methodC");

}

 

 

public static void main(String[] args) {

MyClass myClass = new MyClass();

myClass.methodA();

myClass.methodB();

myClass.methodC();

 

A.methodC();

}

 

 

}



 

package d_poly.array;

 

public class Car {

 

String model;

String color;

int speed;

 

Tire frontLeftTire;

Tire frontRightTire;

Tire backLeftTire;

Tire backRightTire;

 

//인터페이스도 배열의 타입이 될 수 있다.

Tire[] tires;

 

public Car() {

frontLeftTire = new NormalTire();

frontRightTire = new NormalTire();

backLeftTire = new NormalTire();

backRightTire = new NormalTire();

tires = new Tire[] {

new NormalTire(),

new NormalTire(),

new NormalTire(),

new NormalTire()

};

}

 

public void run() {

/*

frontLeftTire.roll();

frontRightTire.roll();

backLeftTire.roll();

backRightTire.roll();

*/

for(Tire tire:tires) {

tire.roll();

}

}

//main 추가

public static void main(String[] args) {

Car car = new Car();

car.run();

System.out.println("===================");

//빗길 주행 타이어로 교체

for(int i = 0; i < car.tires.length ; i++) {

car.tires[i] = new WetTire();

}

car.run();

System.out.println("===================");

//눈길 주행 타이어로 교체

for(int i = 0; i < car.tires.length ; i++) {

car.tires[i] = new SnowTire();

}

car.run();

}

}


 

package d_poly.array;

 

public class NormalTire implements Tire{

 

@Override

public void roll() {

System.out.println("일반 도로를 주행합니다.");

}

 

 

}


 

package d_poly.array;

 

public class SnowTire implements Tire{

 

@Override

public void roll() {

System.out.println("눈길을 달립니다.");

}

 

}


package d_poly.array;

 

public interface Tire {

 

void roll();

 

}


 

package d_poly.array;

 

public class WetTire implements Tire{

 

@Override

public void roll() {

System.out.println("젖은 빗길을 안전하게 주행합니다.");

}

 

}



 

package d_poly.driver;

//세단 - 승용차

public class Sedan implements Runnable{

 

@Override

public void run() {

System.out.println("승용차가 달립니다.");

}

 

}


package d_poly.driver;

 

public class Bus implements Runnable {

 

@Override

public void run() {

System.out.println("버스가 승객을 태우고 달립니다.");

}

 

}


package d_poly.driver;

 

public interface Runnable {

 

void run();

 

}


 

package d_poly.driver;

 

// 차를 사용하는 운전자 객체

public class Driver {

 

public void drive(Runnable runnable) {

runnable.run();

}

}


 

package d_poly.driver;

 

public class DriverExam {

 

public static void main(String[] args) {

Driver driver = new Driver();

Bus bus = new Bus();

driver.drive(bus);

 

Sedan sedan = new Sedan();

driver.drive(sedan);

}

}

 

'Java' 카테고리의 다른 글

generic  (0) 2023.05.04
05.04 Wrapper class, 제네릭  (0) 2023.05.04
05.02 상속, 다형성,protected 접근 제한자, 추상메소드  (0) 2023.05.02
Book  (0) 2023.05.01
캡슐화 숙제  (0) 2023.04.28