# 18. Java 17일차(230907) [국비교육]

brand_mins·2023년 9월 7일

Java

목록 보기
18/47

0. 객체 프로그래밍 특징

  • 캡슐화: 객체의 내부구조 및 데이터를 외부에서 직접 볼 수 없도록 보호하는 것.
  • 다형성: 하나의 객체나 메소드가 여러가지 다른 형태를 가질 수 있음.
  • 상속: 기존의 클래스(부모)를 재활용하여 새로운 클래스(자식)를 작성
  • 추상화: 공통된 특징을 묶어 하나의 클래스로 정의

1. 실습예제

- 도형 구축 프로그램 구현(복습할때 따라쓰면서 학습)
class Shape {
	public static int totalCount = 0;
	public double width = 0;
	public double height = 0;
	
	public Shape() {}
	public Shape(double width, double height) {
		super(); // 모든 클래스는 object를 상속받음.
		this.width = width;
		this.height = height;
	}

	public double area() {
		return width + height;
	}
}

class Rectangle extends Shape {
	public static int totalCount = 0;
	public Rectangle() { }
	public Rectangle(double width, double height) {
		super();
		this.height = height;
		this.width = width;
	}
	@Override
	public double area() {
		return width * height;
	}
	public void addCount() {
		Rectangle.totalCount++;
		Shape.totalCount++;
	}

	@Override
	public String toString() {
		return "Rectangle [width=" + width + ", height=" + height + "]";
	}
	
}

class Triangle extends Shape {
	public static int totalCount = 0;
	public Triangle() { }
	public Triangle(double width, double height) {
		super(height,width);
	}
	@Override
	public double area() {
		return width * height/2;
	}
	public void addCount() {
		Rectangle.totalCount++;
		Triangle.totalCount++;
	}
	@Override
	public String toString() {
		return "Triangle [width=" + width + ", height=" + height + "]";
	}

	
}

public class DrowEx {
	// public Rectangle[] r = new Rectangle[10];
	// public Triangle[] t = new Triangle[10];
	public static Shape[] s = new Shape[20];
	public static boolean isFlag = true;

	public static void main(String[] args) {
		

		while (isFlag) {
			Scanner scanner = new Scanner(System.in);
			System.out.println("1. 삼각형 입력 | 2. 사각형 입력 | 3. 모두 출력 | 4. 종료");
			System.out.print("선택> ");
			String input = scanner.nextLine();
			switch (input) {
			case "1":
				inputTriangle();
				break;
			case "2":
				inputRectangle();
				break;
			case "3":
				displayAll();
				break;
			default:
				isFlag = false;
			}		

		}
		
	}
	
	private static void displayAll() {
    	for(int i=0; i<Shape.totalCount; i++) {
			System.out.println(s[i]);
		}
		System.out.println("삼각형");
		for(int i=0; i<Shape.totalCount; i++) {
			if(s[i] instanceof Triangle) System.out.println(s[i]);
		}
	}
	
	private static void inputRectangle() {
		Scanner scanner = new Scanner(System.in);
		System.out.println("높이");
		int width = Integer.parseInt(scanner.nextLine());
		System.out.println("길이");
		int height = Integer.parseInt(scanner.nextLine());
		s[Shape.totalCount++] = new Triangle(width, height);
		Rectangle.totalCount++;
	}

	private static void inputTriangle() {
		Scanner scanner = new Scanner(System.in);
		System.out.println("높이");
		int width = Integer.parseInt(scanner.nextLine());
		System.out.println("길이");
		int height = Integer.parseInt(scanner.nextLine());
		s[Shape.totalCount++] = new Triangle(width, height);
		Triangle.totalCount++;
	}

}
class Shape {
	public static int totalCount = 0;
	public double width = 0;
	public double height = 0;

	public Shape() {
	}

	public Shape(double width, double height) {
		super(); // 모든 클래스는 object를 상속받음.
		this.width = width;
		this.height = height;
	}

	public double area() {
		return width + height;
	}
}

class Rectangle extends Shape {
	public static int totalCount = 0;

	public Rectangle() {
	}

	public Rectangle(double width, double height) {
		super();
		this.height = height;
		this.width = width;
	}

	@Override
	public double area() {
		return width * height;
	}

	public void addCount() {
		Rectangle.totalCount++;
		Shape.totalCount++;
	}

	@Override
	public String toString() {
		return "Rectangle [width=" + width + ", height=" + height + "]";
	}
}

class Triangle extends Shape {
	public static int totalCount = 0;

	public Triangle() {
	}

	public Triangle(double width, double height) {
		super(height, width);
	}

	@Override
	public double area() {
		return width * height / 2;
	}

	public void addCount() {
		Rectangle.totalCount++;
		Triangle.totalCount++;
	}

	@Override
	public String toString() {
		return "Triangle [width=" + width + ", height=" + height + "]";
	}
}

class ShapeManager {
	public Shape[] s = new Shape[20];
	public boolean isFlag = true;

	private void displayAll() {
		for (int i = 0; i < Shape.totalCount; i++) {
			System.out.println(s[i]);
		}
		System.out.println("삼각형");
		for (int i = 0; i < Shape.totalCount; i++) {
			if (s[i] instanceof Triangle)
				System.out.println(s[i]);
		}
	}

	private void inputRectangle() {
		Scanner scanner = new Scanner(System.in);
		System.out.println("높이");
		int width = Integer.parseInt(scanner.nextLine());
		System.out.println("길이");
		int height = Integer.parseInt(scanner.nextLine());
		s[Shape.totalCount++] = new Rectangle(width, height);
		Rectangle.totalCount++;
	}

	private void inputTriangle() {
		Scanner scanner = new Scanner(System.in);
		System.out.println("높이");
		int width = Integer.parseInt(scanner.nextLine());
		System.out.println("길이");
		int height = Integer.parseInt(scanner.nextLine());
		s[Shape.totalCount++] = new Triangle(width, height);
		Triangle.totalCount++;
	}

	void playMenu() {
		while (isFlag) {
			Scanner scanner = new Scanner(System.in);
			System.out.println("1. 삼각형 입력 | 2. 사각형 입력 | 3. 모두 출력 | 4. 종료");
			System.out.print("선택> ");
			String input = scanner.nextLine();
			switch (input) {
			case "1":
				inputTriangle();
				break;
			case "2":
				inputRectangle();
				break;
			case "3":
				displayAll();
				break;
			default:
				isFlag = false;
			}

		}
	}
}
	public class DrowEx {

		public static void main(String[] args) {
			ShapeManager sm1 = new ShapeManager();
			sm1.playMenu();
			ShapeManager sm2 = new ShapeManager();
			sm2.playMenu();
			ShapeManager sm3 = new ShapeManager();
			sm3.playMenu();
		}
	}

2. Java API

- 이렇게 쓰는 용도이다 확인하고 넘어가기
  • 전문 프로그래머가 만든 클래스 사용방법을 정의해놓은 문서들을 API(Application Program Interface) 혹은 라이브러리임.

(1) String 클래스 API

1) equals 메소드

  • 객체의 문자열 비교
System.out.println("equals 메소드.....");
String str = new String("안녕하세요");
if(str.equals("안녕하세요")) {
	System.out.println("같은 문자열입니다");
} else {
	System.out.println("다른 문자열입니다");
}

2) concat 메소드

  • 두 문자열 합침.
System.out.println("concat 메소드.....");
String str1 = "Hello";
String str2 = "World!";
String str3 = str1.concat(str2);
System.out.println(str3);

3) charAt() 메소드

  • 해당 문자열에서 원하는 인덱스의 문자 출력
System.out.println("charAt 메소드.....");
String str4 = "abcdef";
System.out.println(str4.charAt(2)); // c

4) length 메소드

  • 문자열의 문자 개수 리턴
System.out.println("length 메소드");
String str4 = "abcdef";
System.out.println(str4.length());

5) indexOf() 메소드

  • 매개변수로 넘겨진 문자열과 같은 문자열이 존재하는 인덱스 리턴. 문자열을 찾지 못하면 -1 리턴
System.out.println("indexOf 메소드");
String str4 = "abcdef";
System.out.println(str4.indexOf("cd")); // 2
System.out.println(str4.indexOf("ac")); // -1

6) lastIndexOf() 메소드

  • 매개변수로 넘겨진 문자열의 존재하는 인덱스를 리턴
  • 뒤에서부터 찾기에 문자열을 찾지못하면 -1이 리턴
System.out.println("lastIndexOf 메소드");
String str4 = "abcdef";
System.out.println("bc"); // 1
System.out.println("ac"); // -1

7) substring() 메소드

  • 매개변수로 인덱스를 받아 해당 문자열의 특정부분 추출
System.out.println("substring 메소드......");
String str4 = "abcdef";
System.out.println(str4.substring(3)); // str4 3번 인덱스부터 나머지 출력(def)
System.out.println(str4.substring(2,3)); // c

8) split() 메소드

  • 매개변수로 받은 문자열을 기준으로 문자열을 분리해서 문자열 배열 생성함.
System.out.println("split 메소드....");
String str5 = "사과,배%-바나나-귤";
//문자, % -로 문자열 분리
String arr[] = str5.split("%-"); // 사과, 배와 바나나-귤로 분리
// 문자열 "%-"로 분리
String arr1[] = str5.split("%-");
for (String st:arr) {
	System.out.println(st);
}

9) toLower/UpperCase() 메소드

  • 소문자 혹은 대문자로 변경하여 리턴
System.out.println(".toLowerCase(), toUpperCase 메소드.....");
String str6 = "ABcdef";
System.out.println(str6.toUpperCase()); // ABCDEF
System.out.println(str6.toLowerCase()); // abcdef

10) trim() 메소드

  • 문자열 앞뒤로 공백을 제거하여 문자열 리턴
System.out.println("trim 메소드");
String str7 = "		AB		cd		";
System.out.println(str7.trim());

(2) 자바에서 널리 사용되는 API

- 읽고 넘어가기(프로젝트나 예제풀때 알아두기만 할것)
1. Java SE API(Standard Edition API)
- java.lang: 기본 자바 언어 클래스 및 객체 지향 프로그래밍을 지원하는 클래스가 포함.

- java.util: 유용한 유틸리티 클래스와 자료구조 제공
(예: Scanner의 nextLine())

- java.io: 입출력작업을 위한 클래스와 인터페이스가 포함.

- java.net: 네트워크 프로그래밍을 위한 클래스와 인터페이스가 제공.

- java.sql: 데이터베이스 액세스를 위한 JDBC(Java Database Connectivity)가 포함되어 있음.

2. Java EE API(Enterprise Edition API)
- 대규모 기업 애플리케이션 개발하기 위한 것.
- 서버측 애플리케이션 지원(JSP,Servlet)

3. JavaFx API
- 데스크톱 및 리치 인터페이스 애플리케이션 개발

4. Android API
- 안드로이드 앱 개발을 위한 API

5. Java collections Framework
- 컬렉션 데이터 구조를 다루기 위한 API구조
- List, Set, Map 등과 같은 자료구조 제공

6. Java Swing API
- 데스크톱 애플리케이션의 그래픽 사용자 인터페이스(GUI)를 구축하기 위한 API

7. Java NIO (New I/O) API
- 비동기 입출력 및 블록되지 않는 입출력 지원 API

8. Java XML API
- XML문서를 읽고 쓰는데 사용하는 API

9. Java Security API
- 보안 관련 작업을 수행하기 위한 API
- 암호화, 인증, 권한부여 등 다룸

10. Java 2D API 및 Java 3D API
- 2D 및 3D 그래픽 렌더링을 위한 API
- 그래픽 애플리케이션 지원

3. Wrapper 클래스

  • 기본 자료형을 클래스로 만듬
  • 용도: integer 관련 정보를 클래스로 추가해 생성함.
  • 컬렉션 프레임워크와 제네릭을 배우면 Wrapper 클래스 사용
int a;
Integer b;
b = 10;
b = b+10;

4. 다형성 추가예제

- chat-gpt가 만든 예제 참고하여 학습함.
- ArrayList를 활용하였음.
- 배우지 않은 부분이 있어서 코드 확인만 할것.
import java.util.ArrayList;
import java.util.List;

abstract class Shape1 {
	public abstract double calculateArea();
}

class Circle extends Shape1 {
	private double radius = 0;
	private static final double PI = 3.14;
	public Circle(double radius) {
		this.radius = radius;
	}
	@Override
	public double calculateArea() {
		return PI * radius * radius;
	}
	
}

class Rectangle1 extends Shape1 {
	private double width = 0;
	private double height = 0;
	
	public Rectangle1(double width, double height) {
		this.width = width;
		this.height = height;
	}

	@Override
	public double calculateArea() {
		return width * height;
	}
	
}


public class Polymor {

	public static void main(String[] args) {
		List<Shape1> shapes = new ArrayList<>();
		shapes.add(new Circle(5.0));
		shapes.add(new Rectangle1(4.0,6.0));
		
		for(Shape1 shape : shapes) {
			double area = shape.calculateArea();
			System.out.println("도형의 넓이: " + area);
		}
		

	}

}
profile
IT 개발자가 되기 위한 기록

0개의 댓글