SQLD, ECLIPS, JAVA,PYTHON, NODE....

[Eclips] Java Class 7 - toString, 추상클래스(abstract), 인터페이스(interface) 본문

Java

[Eclips] Java Class 7 - toString, 추상클래스(abstract), 인터페이스(interface)

D_Aiden 2023. 12. 15. 11:12
728x90
반응형
SMALL

2023.12.15

#추상클래스 abstract

- 다형성, 상속을 활용해 확장 가능구조를 만들 수 있도록 도와주는 중요한 개념.
- 호출방식: abstract 사용, 추상메서드는 선언만 하고 본체는 정의하지 않음
- new 안됨
- 역할: 객체의 공통된 특성을 묶어서 표현, 이를 상속받는 하위 클래스에서 구체적 내용을 구현하도록 유도하는 역할.
- 자식들에게 공통정보 제공(맴버변수), 추상메소드 제공(자식이 재정의 하도록)
- 추상 클래스(Abstract Class)는 일반 클래스와는 다르게 하나 이상의 추상 메서드를 포함, 인스턴스를 직접 생성할 수 없는 클래스
- 특징:
1) 인스턴스 생성 불가능: 직접 인스턴스를 생성할 수 없음. 반드시 구체적인 클래스를 통해 객체생성.
2) 추상 메서드 구현 강제: 추상 클래스가 포함하는 추상 메서드는 하위 클래스에서 반드시 구현되어야 함. 이를 통해 추상 클래스를 상속받는 클래스들이 공통된 메서드를 가져야 하며, 각 클래스가 자신만의 특화된 동작을 구현할 수 있도록.
3) 일반 메서드 포함가능: 추상 클래스는 추상 메서드 외에도 일반 메서드를 포함할 수 있습니다. 이 일반 메서드들은 하위 클래스에서 그대로 사용하거나 오버라이딩할 수 있습니다.

abstract class Shape { 							// 추상 클래스
    abstract double calculateArea();		    // 추상 메서드
	void display() { 							// 일반 메서드
        System.out.println("도형을 출력합니다.");
    }
}

// 추상 클래스를 상속받는 구체적인 클래스
class Circle extends Shape { 		    	// 추상 메서드의 구현
    double calculateArea() {
        double radius = 5;
        return Math.PI * radius * radius;
    }
}
class Rectangle extends Shape {			   	// 추상 메서드의 구현
    double calculateArea() {
        double length = 4;
        double width = 3;
        return length * width;
    }
}

public class Main {
    public static void main(String[] args) {	    // 추상 클래스의 인스턴스 생성할 수 없음
        // Shape shape = new Shape(); 				// 에러(추상 클래스 인스턴스 생성 못하므로)

		Circle circle = new Circle();         // 추상 클래스를 상속받은 구체적인 클래스의 인스턴스 생성
        System.out.println("원의 면적: " + circle.calculateArea());
        circle.display();
        Rectangle rectangle = new Rectangle();
        System.out.println("사각형의 면적: " + rectangle.calculateArea());
        rectangle.display();
    }
}

 

## 인터페이스 interface

- 정의 :  인터페이스(Interface)는 Java에서 추상화를 구현하기 위한 도구 중 하나로, 추상 메서드의 집합.
              클래스 간의 결합도를 낮추고 유연성을 높일 수 있도록 도와줌.

인터페이스 상속구조
A a = new (b,c,f,e)
B b = new (b,c)
C c = new (c)
D d = new (b,c,e,f)
E e = new (e,f)
F f = new (f)
 

interface Mammal {
    void feed();
}
interface Pet extends Animal, Mammal { 		//인터페이스간 상속. extends는 부모하나만 가능
    void play();
}


- 호출방식: implements 사용

// 인터페이스 구현
class Dog implements Animal {  			// implements 사용(추상 메서드 호출)
    public void makeSound() {  			// 인터페이스의 추상 메서드 구현
        System.out.println("멍멍!");

1) 다형성의 꽃이라 지칭.
2) 클래스가 인터페이스를 구현(Implements)하면, 해당 클래스는 인터페이스에서 정의된 모든 추상 메서드를 구현.
3) 다중상속 가능. 클래스가 여러 인터페이스 구현 가능.
4) 추상 메서드를 갖음. 인터페이스가 구현된 클래스는 반드시 인터페이스에서 정의된 모든 추상 메서드 구현 가능.
5) 인터페이스는 다른 인터페이스를 상속 가능.
- 외부에 배포할 용도에 주로 사용
- 전체 시스템의 통일성(자식클래스가 재정의(오버라이딩) 하도록)의 특징으로 주로 사용
- 허용범우: 상수형변수추상메소드만 가능

// 인터페이스 선언
interface Animal {
    void makeSound();   // 추상 메서드

// 인터페이스에서는 상수형 변수 선언가능
    String TYPE = "Animal";
}

// 인터페이스 구현
class Dog implements Animal {  // implements 사용(추상 메서드 호출)
    public void makeSound() {   // 인터페이스의 추상 메서드 구현
        System.out.println("멍멍!");
    }
}
class Cat implements Animal {
    public void makeSound() {
        System.out.println("야옹!");
    }
}
public class Main {
    public static void main(String[] args) {
        Dog myDog = new Dog();        // 인터페이스를 구현한 클래스의 인스턴스 생성
        Cat myCat = new Cat();		  // 인터페이스를 구현한 클래스의 인스턴스 생성
        myDog.makeSound(); // 멍멍!	// 메서드 호출
        myCat.makeSound(); // 야옹!   // 메서드 호출
        System.out.println("동물의 종류: " + Animal.TYPE);      // 인터페이스에서 선언한 상수 사용
    }
}
package oop.ItemEx;
//2.인터페이스 구현
public interface ItemInterface {

	final static int ITEM_INTERFACE =1;
	final static int ITEM_NORMAL = 0;
	
//1.추상클래스	
	abstract void Itemshow(String itenNo, String title, String price);
	abstract void ItemBasicName();
	
	public void Rent(String a, String b);
}
package oop.ItemEx;
//부모 클래스
abstract public class Item	implements ItemInterface {                  
	String itemNo, title, price, borrower, checkOutDate;
	byte state;
	
	public Item(String itemNo, String title, String price) {
		this.itemNo = itemNo;
		this.title = title;
		this.price = price;
	}	
	public void output() {
		System.out.println("상품정보 : "+ itemNo);
		System.out.println("제목: "+ title);
		System.out.println("가격: " + price);
	}
	public void CdOutPut() {
		System.out.println("CD제품번호 :"+ itemNo);
		System.out.println("CD가격: " + price);
	}

//아이템 정보	
	public void ItemShow() {
		System.out.println("구매할 물건번호 입력하세요.: ");
		System.out.println("구매할 제목 : ");
		System.out.println("구매 가격 : ");
	}
// 아이템 기본이름
	public void ItemBasicName() {
	}
}
package oop.ItemEx;
//자식1 클래스
public class CD	extends Item implements ItemInterface{
	String singer, outDate, trackNum;
	String RentDate, Cdtype;
	byte state;

	public CD(String itemNo, String title, String price, String singer, String trackNum, String outDate) {
		super(itemNo, title, price);
		this.singer = singer;
		this.trackNum = trackNum;
		this.outDate = outDate;
	}
	public void ItemShow() {
		super.ItemShow();
		System.out.println("CD가수는" +singer);
	}	

	public void output() {
		System.out.println("CD번호 : "+ itemNo);
		System.out.println("CD제목: "+ title);
		System.out.println("CD가격: " + price);	
	}
	public void Rent(String RentDate, String Cdtype) {
		if(state!=ITEM_INTERFACE) {
			return;
		}
		this.RentDate=RentDate;
		this.Cdtype=Cdtype;
		this.state=ITEM_NORMAL;
		System.out.println("\n"+itemNo+"/"+ title +"이(가) 대여 되었습니다.");
		System.out.println("렌트일자: " + RentDate);
		System.out.println("Cd타입: " + Cdtype);

	}
	@Override
	public void Itemshow(String itenNo, String title, String price) {
		// TODO Auto-generated method stub
		
	}
}

//	public void ItemShow() {
//		super.ItemShow();
//		System.out.println("CD는" + cd);
//	}	
//	public void ItemBasicName() {	
//		System.out.println("CD아이템번호 : "+ itemNo);
//		System.out.println("CD제목 : "+ title);
//		System.out.println("CD가격 : "+ price);
//	}
//}

package oop.ItemEx;
//자식2 클래스
public class DVD extends Item implements ItemInterface{
	String actor, runtime, outDate1;
	String RendOfDvd, Datesss;
	byte state;

	public DVD(String itemNo, String title, String price, String actor, String runtime, String outDate1) {
		super(itemNo, title, price);
		this.actor=actor;
		this.runtime=runtime;
		this.outDate1=outDate1;
	}	
	public void ItemShow() {
		super.ItemShow();
		System.out.println("DVD배우: " +actor);
	}	
	public void ItemBasicName() {	
		System.out.println("DVD번호: "  + itemNo);
		System.out.println("DVD제목: " + title);
		System.out.println("DVD가격: " + price);
	}
	public void Rent(String DVDRentss, String Dates) {
		if(state !=ITEM_INTERFACE) {
			return;
		}
		this.RendOfDvd=DVDRentss;
		this.Datesss=Dates;
		this.state=ITEM_NORMAL;
		System.out.println("\n"+itemNo+"/"+ title +"이(가) 대여 되었습니다.");
		System.out.println("렌트일자: " + RendOfDvd);
		System.out.println("Cd타입: " + Datesss);
	}
	@Override
	public void Itemshow(String itenNo, String title, String price) {
		// TODO Auto-generated method stub
		
	}
}

package oop.ItemEx;
//자식3 클래스
public class Book extends Item implements ItemInterface{
	String name, pageNum, outDate2;		//맴버변수
	String borrower, checkOutDate;
	byte state;


	public Book(String itemNo, String title, String price, String name, String pageNum, String outDate2) {
		super(itemNo, title, price);
		this.name=name;
		this.pageNum=pageNum;
		this.outDate2=outDate2;
	}	

	public void ItemShow() {
		super.ItemShow();
		System.out.println("Book이름은" + name);
	}	
	public void ItemBasicName() {	
		System.out.println("Book번호: "+ itemNo);
		System.out.println("Book제목: "+ title);
		System.out.println("Book가격 : " + price);
	}

	public void Rent(String borrower, String checkOutDate) {
		if(state != ITEM_INTERFACE) {
			return;
		}
		this.borrower=borrower;
		this.checkOutDate=checkOutDate;
		this.state=ITEM_NORMAL;
		System.out.println("\n"+itemNo+"/"+title+"이(가) 대여 되었습니다.");
		System.out.println("대여한 사람: " + borrower);
		System.out.println("대여날짜: " + checkOutDate);
	}

	@Override
	public void Itemshow(String itenNo, String title, String price) {
		// TODO Auto-generated method stub
		
	}
}
package oop.ItemEx;
//메도스(=함수)를 컨트롤 할 메소드
import java.util.Scanner;
public class Handler {
	private Item[] myItems;
	public int numOfItem;

	public void ItemHandler(int num) {
		myItems = new Item[num];
		numOfItem=0;
	}

	private void addItemInfo(Item I) {
		myItems[numOfItem++] = I;
	}

	public void addItem(int choice) {
		String singer, trackNum, outDate, actor, runtime, outDate1, name, pageNum, outDate2;

		Scanner scan= new Scanner(System.in);

		System.out.println("아이템 번호: "); String itemNo = scan.nextLine();
		System.out.println("아이템 제목: "); String title = scan.nextLine();
		System.out.println("아이템 가격: "); String price = scan.nextLine();
		if(choice==1) {
			System.out.println("CD가수명: "); singer=scan.nextLine();
			System.out.println("CD트렉번호: "); trackNum=scan.nextLine();
			System.out.println("CD발매일: "); outDate=scan.nextLine();
			addItemInfo(new CD(itemNo, title, price, singer, trackNum, outDate));
		} else if(choice==2) {
			System.out.println("DVD배우: ");actor=scan.nextLine();
			System.out.println("DVD런타임: "); runtime=scan.nextLine();
			System.out.println("DVD발매일: "); outDate1=scan.nextLine();
			addItemInfo(new DVD(itemNo, title, price,actor, runtime, outDate1));
		} else if(choice==3) {
			System.out.println("Book책이름: "); name=scan.nextLine();
			System.out.println("Book페이지수: "); pageNum=scan.nextLine();
			System.out.println("Book발간일: "); outDate2= scan.nextLine();
			addItemInfo(new Book(itemNo, title, price,name, pageNum, outDate2));
		}	
	}

	public void showAllDate() {
		for(int i=0; i<myItems.length; i++) {
			myItems[i].ItemBasicName();
		}
	}

	public void RentAllDate() {

		for(Item leen : myItems) {
			leen.Rent("aiden","123");
		}
	}

}

 

728x90
반응형
LIST