-일종의 추상클래스, 추상클래스(미완성 설계도)보다 추상화 정도가 높다.
-실제 구현된 것이 전혀 없는 기본 설계도,(알맹이 없는 껍데기)
-추상메서드와 상수만을 멤버로 가질 수 있다.
-인스턴스를 생성할 수 없고, 클래스 작성에 도움을 줄 목적으로 사용된다.
-미리 정해진 규칙에 맞게 구현하도록 표준을 제시하는 데 사용된다.
-'class'대신 'interface'를 사용한다는 것 외에는 클래스 작성과 동일하다.
-하지만, 구성요소(멤버)는 추상메서드와 상수만 가능하다.
-인터페이스도 클래스처럼 상속이 가능하다.(클래스와 달리 다중상속 허용)
-인터페이스는 object클래스와 같은 최고 조상이 없다.
-인터페이스를 구현하는 것은 클래스를 상속받는 것과 같다.
다만, extends대신 implements를 사용한다
-인터페이스에 정의된 추상메서드를 완성해야 한다.
-상속과 구현이 동시에 가능하다.
-인터페이스 타입의 변수로 인터페이스를 구현한 클래스의 인스턴스를 참조할 수 있다.
-인터페이스를 메서드의 매개변수 타입으로 지정할수있다.
-인터페이스를 메서드의 리턴타입으로 지정할수있다.
new-interface
테란 패키지
-airunit 클래스-
public class AirUnit extends Unit {
AirUnit(int hp){
super(hp);
}
}
-tank클래스-
public class Tank extends GroundUnit implements Repairable {
Tank(){
super(150);
this.hitPoint = this.MAX_HP;
}
@Override //어노테이션? 컴파일러에게 지금 적는 메서드는 오버라이드 하는 메서드라고 컴파일러에게 알려주는거임
public String toString() {
return "Tank";
}
}
-marine클래스-
public class Marine extends GroundUnit {
Marine(){
super(40);
this.hitPoint = this.MAX_HP;
}
}
-groundunit 클래스-
public class GroundUnit extends Unit {
GroundUnit(int hp){
super(hp);
}
}
-unit클래스-
public abstract class Unit {
int hitPoint;
final int MAX_HP;
Unit(int hp){
MAX_HP = hp;
}
}
-repairable 클래스-
코드를 입력하세요
-SCV클래스-
public class SCV extends GroundUnit implements Repairable {
SCV(){
super(60);
this.hitPoint = this.MAX_HP;
}
void repair(Repairable r) {
if(r instanceof Unit) { //unit 타입인지 검사
Unit u = (Unit)r; //unit타입이면 형변환
while(u.hitPoint != u.MAX_HP){ //maxpoint가될때까지 1씩 증가
u.hitPoint++;
}
}
}
}
-EX 클래스-
public class Ex {
public static void main(String[] args) {
Tank tank = new Tank();
Marine marine = new Marine();
SCV scv = new SCV();
scv.repair(tank);
//scv.repair(marine);
}
}
-yourinterface 클래스-
public interface YourInterface {
int num = 1234;
static void staticMethod() {
System.out.println("staticMethod");
}
default void defaultMethod() {
System.out.println("defaultMethod");
}
void abstractMethod();
}
-EX22 클래스-
public class Ex22 implements YourInterface {
public void abstractMethod() {
System.out.println("abstractMethod()");
}
public static void main(String[] args) {
//Ex22 ex22 = new Ex22();
YourInterface your = new Ex22();
//System.out.println("num: "+ex22.num);
//System.out.println("num: "+your.num); //인터페이스 이름으로 호출하는것을 권장함!
System.out.println("num: "+YourInterface.num); //인터페이스 이름으로 호출하는것을 권장함!
//ex22.staticMethod();
YourInterface.staticMethod();
your.defaultMethod();
//ex22.defaultMethod();
your.abstractMethod();
//ex22.abstractMethod();
}
}
-클래스 안에 선언된 클래스
-특정 클래스 내에서만 주로 사용되는 클래스를 내부 클래스로 선언한다.
-GUI어플리케이견(A WT,Swing)의 이벤트처리에 주로 사용된다.
-내부 클래스의 종류는 변수의 선언위치에 따른 종류와 동일하다.
-유효범위와 성질도 변수와 유사하므로 비교해보면 이해하기 쉽다.
//mycalendar 클래스
public class MyCalendar {
private int year;
private int month;
private int day;
MyCalendar(int year,int month,int day){
this.year = year;
this.month = month;
this.day = day;
}
//윤년 여부 판단 메서드
private boolean isLeapYear() {
return this.isLeapYear(this.year);
}
private boolean isLeapYear(int year) {
boolean result = false;
if(year % 4 ==0 && year % 100 != 0 || year % 400 == 0 ) {
result = true;
}
return result;
}
//각 월의 마지막날 반환하는 메서드
int getMonthLastDay(int month) {
int [] monthLastDays = {-1,31,28,31,30,31,30,31,31,30,31,30,31};
if(this.isLeapYear()) {
monthLastDays[2] = 29;
}
return monthLastDays[month];
}
//1년1월1일부터 사용자가 입력한 날짜까지의 전체 총 일수를 반환하는 메서드
int getTotalDays() {
int totalDays = 0;
//사용자가 입력한 전년도 까지의 총 일수 계산 ↓
for(int i =1; i<this.year; i++) {
if(this.isLeapYear()) {
totalDays += 366;
}else {
totalDays += 365;
}
}
//사용자가 입력한 년의 1월부터 입력한 전월까지의 총일수 ↓
for(int i = 1; i< this.month; i++) {
totalDays += this.getMonthLastDay(i);
}
//사용자가 입력한 월의 입력한수 일까지의 총 일수 ↓
totalDays += this.day;
return totalDays;
}
//요일을 반환하는 메서드 ↓
public String getDayOfWeek() {
String [] dayOfWeek = {"일","월","화","수","목","금","토"};
return dayOfWeek[this.getTotalDays() % 7];
}
}
//출력 코드 exam1 클래스
package chap07;
import java.util.Scanner;
/*
사용자에게 년,월,일을 입력 받아 일자의 요일을 반환하는 프로그램을 작성하세요.
단, 반드시 객체지향적인 코드로 작성하여야 합니다.
<실행예>
년,월,일을 입력하세요: 2023 6 12
입력하신 2023년 6월 12일은 월요일 입니다.
*/
public class Exam1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
MyCalendar calendar;
int year,month,day= 0;
System.out.printf("년도와 월과 일 입력하세요: ");
year = sc.nextInt();
month= sc.nextInt();
day = sc.nextInt();
calendar = new MyCalendar(year,month,day);
System.out.printf("입력하신 %d년의 %d월의 %d일은 %s요일 입니다.",year,month,day,calendar.getDayOfWeek());
sc.close();
}
}
//mylotto 클래스
public class MyLotto {
private int [] lotto;
public MyLotto(){
this.lotto = new int[6];
this.setLotto();
this.sortLotto();
}
//로또번호 중복검사 메서드 ↓
boolean isUnique(int num) {
boolean result = true;
for(int i=0; i<this.lotto.length; i++) {
if(this.lotto[i] == num) {
result = false;
break;
}
}
return result;
}
//로또배열 초기화 메서드 ↓
void setLotto() {
int temp;
for(int i = 0; i<this.lotto.length;) {
while(true) {
temp = (int)(Math.random() * 45)+1 ;
if(this.isUnique(temp)) {
lotto[i] = temp;
i++;
break;
}
}
}
}
//순서대로 선택정렬하는 메서드 ↓
void sortLotto() {
int temp;
for(int i = 0; i<this.lotto.length-1; i++) {
for(int j=i+1; j<this.lotto.length; j++) {
if(lotto[i] > lotto[j]) {
temp = lotto[i];
lotto[i] = lotto[j];
lotto[j] = temp;
}
}
}
}
//배열을 반환하는 getlotto
int[] getLotto() {
return lotto;
}
public String toString() { //tostring 메서드 오버라이딩
String result = "";
for(int num : lotto) {
result += num + " ";
}
return result;
}
}
//exam2 출력 클래스
package chap07;
/*
* 다음의 배열을 이용하여 중복되지 않는 로또 번호 6개를 생성하여 크기 순서대로 출력하는 코드를 작성하세요.
* 단, 객체지향적으로 작성하여야 합니다.
*
* int[] lotto = new int[6];
*/
public class Exam2 {
public static void main(String[] args) {
MyLotto lotto = new MyLotto();
System.out.println("로또번호: "+lotto);
}
}
자바의 정석-남궁성 참고