■ 상속 - 2
package day05_01;
// 부모 : Animal move()
// 자녀 : Bird sing()
class Animal{
public void move() {
System.out.println("움직인다.");
}
}
class Bird extends Animal{
public void sing() {
System.out.println("노래한다.");
}
}
public class sangsok2 {
public static void main(String[] args) {
Animal a1 = new Animal();
a1.move();
Bird b1 = new Bird();
b1.move();
b1.sing();
}
}
■ 상속 - 3
package day05_01;
// 상속에서
// 부모클래스, parent class, base class, 기본클래스
// 자녀클래스, Child class, derived class, 파생클래스
// unified modeling language
class Parent{
String juso;
public Parent() { // 디폴트 생성자, 인자 x 생성자
System.out.println("나도 주소 물어봐줘");
}
public Parent(String juso) { // 인자 o 생성자
System.out.println("잘왔구먼 내 주소는 " + juso + "야 ");
}
public void don() {
System.out.println("나 돈이 많아!");
}
}
// this. this() super. super()
class Child extends Parent{
int na2;
public void car() {
System.out.println("나 신형차 있다!");
}
public Child() { // 디폴트 생성자
}
public Child(String juso, int na2) {
super(juso);
this.juso = juso;
this.na2 = na2;
}
}
public class sangsok3 {
public static void main(String[] args) {
Parent p1 = new Parent();
Child c1 = new Child();
p1.don();
c1.don();
c1.car();
// ----------------------------------------------
Child c2 = new Child("종로", 30); // 기본적으로 자녀쪽에서 주소, 나이 사용이 가능?
System.out.println(c2.juso + "\t" + c2.na2);
// <상속에서의 생성자 호출>
// 생성자는 부모클래스의 생성자를 먼저 찾아가야 한다. 부모쪽의 생성자를 먼저 처리.
// 그렇게 하지 않으면 부모의 생성자를 처리할 방법이 없음.
// 부모의 생성자가 2개인 경우 디폴트 생성자가 실행된다.
// parameter가 있는 생성자를 실행시키기 위해서는 super를 통해 호출
}
}
<결과>
나도 주소 물어봐줘
나도 주소 물어봐줘
나 돈이 많아!
나 돈이 많아!
나 신형차 있다!
잘왔구먼 내 주소는 종로야
종로 30
■ 상속 - 4 (형변환)
package day05_02;
// 자료의 형변환
// int <-- short
// short <-- (short)int
class Parent{
}
class Child extends Parent{
}
public class AJ005_01_OOP {
public static void main(String[] args) {
Parent p1 = new Parent();
Child c1 = new Child();
// Parent p2 = c1; // O
Parent p2 = new Child(); // O
// Child c2 = p1; // X
// Child c2 = new Parent(); // X
// Child c3 = p2; // 자기 자신이지만 빨간 줄이 뜬다.
Child c3 = (Child)p2; // O 따라서 (Child)를 통해 확실하게 표시해준다.
// Child c3 = (Child)new Child();
// Child c5 = p1;
// Child c5 = (Child)p1;
// ㄴ compiler ok / run x
// 앞에 부모가 오면 형변환 가능
}
}
■ 오버라이딩
package day05_03;
import java.util.Scanner;
// overriding, 재정의, 가상메소드(VIRTUAL)
// 1) 상속에서 메소드 이름이 같아야
// 2) 재정의시 약간 다르게 하는 것
class Parent{
public void car() {
System.out.println("부모차 타고 드라이브 가자!");
}
}
class Child extends Parent{
public void car() {
System.out.println("자녀차 타고 세계여행 가자!");
}
}
public class AJ005_02_Overriding {
// 다음처럼 진행되도록 프로그램을 작성하되 객체의 형변환을 사용하시오.
// 어느 차를 타시렵니까? (1-부모, 2-자녀)
// 1 - 부모차 타고 드라이브 가자
// 2 - 자녀차 타고 세계여행 가자
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("어느차를 타시렵니까? (1.부모차/2.자녀차) : ");
int sel = sc.nextInt();
Parent p77 = null;
switch(sel) {
case 1:
p77 = new Parent();
p77.car();
break;
case 2:
p77 = new Child(); // p77 = 자식객체 범위가 넓어졌다.
p77.car();
break;
default:
System.out.println("정확한 숫자를 입력해주세요.");
}
}
}
■ try - catch
package day06_1;
import java.util.Scanner;
public class Ex {
public static void main(String[] args) {
// 예외 :Exception (내장 클래스, 예외 클래스 중의 조상)
// try {} : 예외날지도 몰라
// catch {} : 예외 시 처리하기
// finally {} : 무조건 처리
try {
Scanner sc1 = new Scanner(System.in);
System.out.print("첫 번째 수는 : "); // 0
String one1 = sc1.nextLine();
int soo1 = Integer.parseInt(one1);
System.out.print("두 번째 수는 : "); // 0
String two1 = sc1.nextLine();
int soo2 = Integer.parseInt(two1);
System.out.println(soo1 / soo2);
} catch(ArithmeticException e) { // 세부적으로 체크
System.out.println("0이 아닌 값으로 입력");
} catch(NumberFormatException e) {
System.out.println("형이 말할게. 숫자로 입력해줘");
System.out.println(e);
System.out.println(e.getMessage());
} catch(Exception e) {
System.out.println("에러가 났네");
System.out.println("저기요 0이 아닌 두 정수를 입력해주세요");
System.out.println(e.getMessage()); // by zero
System.out.println(e);
//c : errno(4069) perror
//java: message getMessage
} finally {
System.out.println("굿");
//db 접속 close, 네트워크 접속 close
}
// 0/0 -> 부정
// 0/30 -> 0F
// 30/0 -> 불능
}
}
■ 다중상속
package day06_1;
interface Komo{ // 선언은 인터페이스. 구현은 상속받는 곳
public void gold();
}
interface Samchon {
public void yoat(); //선언
}
// 인터페이스는 Class 위에 있어야 한다.
class Parent {
public void don() {
System.out.println("나 재산 많아");
}
}
class Na extends Parent implements Komo, Samchon{
public void kumko() {
System.out.println("나 금고 많아 ");
}
@Override
public void yoat() {
System.out.println("삼촌한테 요트 상속 받음");
}
@Override
public void gold() {
System.out.println("고모한테 금 상속 받음");
}
}
public class Multi_Inheritance {
public static void main(String[] args) {
/*
다중 상속이 안 되는 이유
: diamond problem
*/
Parent p1 = new Parent();
Na n1 = new Na();
n1.don(); // extends 부모
n1.gold(); // interface 고모
n1.yoat(); // interface 삼촌
//interface : 다중상속, 원형, 협업
}
}
■ indexOf
package review.jav;
public class IndexOf {
public static void main(String[] args) {
String s1 = "ondal";
System.out.println(s1.charAt(1)); // 첫 번째 글자가 뭐야? : n
System.out.println(s1.indexOf("da")); // "da"의 d의 위치 ==> da 글자가 포함되어 있어?
String [] bae = {"java Programming",
"C# programming",
"easy Java Programming",
"Master of JAVA",
"C Language and java",
"Power Builder",
"Oracle and Java-JDBC"
};
int sw = 0;
for(int i=0; i<bae.length; i++) {
if(bae[i].toUpperCase().indexOf("JAVA") >= 0) {
System.out.println(bae[i]);
sw = 1;
}
}
if(sw == 0)
System.out.println("검색하신 책은 재고가 없습니다. ");
}
}
■ Abstract
package review.jav;
//추상클래스는 interface와 사촌 (interface는 대충 만든 설계도)
//객체의 형변환 : 부모가 자식꺼를 가지는..
abstract class Kwail{ // abstract 때문에 추상클래스로 변환
public void good() {
System.out.println("먹으면 good");
}
public abstract void meokja(); // 추상메소드, 추상클래스는 최소 하나의 추상메소드를 가져야 한다.
}
class Sakwa extends Kwail{
@Override
public void meokja() {
System.out.println("사과를 사각사각 먹자");
}
}
class Bae extends Kwail{
@Override
public void meokja() {
System.out.println("배는 잠수함 모양으로 예쁘게 깎아서 먹자");
}
}
class Kam extends Kwail{
@Override
public void meokja() {
System.out.println("감은 꼭지 떼고 맛있게 먹자");
}
}
public class AbstractEx {
public static void main(String[] args) {
/* 추상화
<과일>
사과 배 감
*/
// Kawil k = new Kwail(); 추상
Kwail k1 = new Sakwa();
k1.meokja();
Kwail k2 = new Bae();
k2.meokja();
Kwail k3 = new Kam();
k3.meokja();
// 같은 meokja()인데
// ==> 다형성
// 업무상, 유사한 업무차리를 할 때
// 버전을 선택하거나 업그레이드할 때
}
}
■ 검색
* search
* 1) sequence search (순차검색)
* (1 + 100) / 2 = 50 (n+1)/2 횟수 공식 50회
* 2) binary search (이진검색)
* log 2(n) + 1
* 2^6 = 64 2^x=100 2^7=128
* 2^x = 100 6~7회
* sort 가 되어있으면
* 12 45 67 89 92 95 100 찾으려는 수는 92
* 가운데 89 선택 -> 92보다 작음 -> 89보다 아래인 수사들 다 검색대상에서 제외 -> 92 95 100
* 95 선택 100 제외
* 92 선택
* 3) fibonacci search
* 피보나치 수열을 기준으로 찾는 것
□ 순차검색과 이진검색
package review.jav;
import java.util.Arrays;
public class Search {
public static void main(String[] args) {
// 1) sequence search (순차검색)
int [] soo = {100, 120, 50, 120, 70}; // 초기치
// 50을 찾아보자
int fsoo = 50;
for(int i=0; i<soo.length; i++) {
if(soo[i] == fsoo) {
System.out.println(i + "번째"); // 중복있는 수를 고려하여 break 안 함
}
}
// 2) binary search (이진검색)
int [] soo2 = {100, 120, 50, 120, 70}; // 초기치
Arrays.sort(soo2); // {50, 70, 100, 120, 120}
// 100이 몇 번째?
System.out.println(Arrays.binarySearch(soo2, 100) + "번째에 있다.");
// 80이 몇번째?
System.out.println(Arrays.binarySearch(soo2, 80) + "번째에 있다");
// 음수가 나오면 없는 것
if(Arrays.binarySearch(soo2, 80) >= 0) { // 80이 배열에 있어?
System.out.println(Arrays.binarySearch(soo2, 80) + "번째에 있구나");
}else {
System.out.println("없어!");
}
}
}
■ Collection
// 배열 : 고정길이, 자료형이 결정
// 컬렉션 : 가변길이, 자료형도 다양(List, Map, Set)
// generic : 가변길이, 자료형 고정
/*
* Array : 고정길이 배열, one data type
* Collection : 가변길이배열, multi data type
* Generic(제네릭) : 가변길이배열, one data type
*
* (참고) generic : 자바(전체출력, 나이가 30이상, 성이 김씨...)
* - JDBC(Java DataBase Connectivity) 회원명단(DB)
*
* List : 순서 o, 중복 o,
* ㄴ vector, ArrayList, LinkedList, Stack, Queue
*
* Map : key-value
* ㄴ HashMap, TreeMap, LinkedHashMap, SortMap
*
* Set : 순서 x, 중복 x
* ㄴ HashSet, LinkedHashSet, TreeSet, SortedSet
*
*
*/
□ 컬렉션 - 1 (with제너릭)
package day10.collection;
import java.util.ArrayList;
class Car{
// 필드
private String color;
private int door;
public Car() { // 디폴트 생성자
}
public Car(String color, int door) { // 생성자
super();
this.color = color;
this.door = door;
}
// getter & setter
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getDoor() {
return door;
}
public void setDoor(int door) {
this.door = door;
}
// toString
public String toString() {
return "자동차 색은 " + color + "이고 문의 개수는 " + door + "개입니다.";
}
}
public class B_collection_generic {
public static void main(String[] args) {
// ArrayList + generic(Car class)
// ArrayList alist1 = new ArrayList(); ==> 컬렉션
// 여기에 generic을 포함하면
ArrayList<Car> alist1 = new ArrayList<Car>();
// Car 클래스 객체를 만들고 + ArrayList에 넣어보자
// Car myCar = new Car("red", 4);
// ㄴ 여기서 필요없는 객체참조변수 myCar를 생략하면
alist1.add(new Car("black", 5));
alist1.add(new Car("red", 2));
alist1.add(new Car("blue", 4));
alist1.add(new Car("pink", 4));
alist1.add(new Car("yellow", 10));
alist1.add(new Car("purple", 7));
alist1.add(new Car("green", 3));
alist1.add(new Car("white", 1));
// 자바로는 직접 값을 넣지만 JDBC에서는 DB에서 읽어와서 컬렉션에 넣음.
// 전체 차가 팔린 현황을 출력하시오.
for(int i=0; i<alist1.size(); i++) {
System.out.println(alist1.get(i));
// alist1.get(0)은 myCar 역할하는 값이므로 sysout(myCar)
// sysout(myCar) = sysout(myCar.toString())
}
System.out.println();
// toString 사용하지 않고 color만 모두 출력
for(int i=0; i<alist1.size(); i++) {
System.out.println(alist1.get(i).getColor());
}
// toString 사용없이 문의 수가 4개라고 되어있는 것, 색과 문의 갯구 모두 출력하기
for(int i=0; i<alist1.size(); i++) {
if(alist1.get(i).getDoor() == 4) {
System.out.println("자동차 색 : " + alist1.get(i).getColor() + " 문의 개수 : " + alist1.get(i).getDoor());
}
}
System.out.println();
// CRUD(삽입, 검색, 수정, 삭제)는 개발에서 필수사항인데
// 지금 이 기법은 "전체검색"과 연관된 프로그램에 유용하게 사용
// DB ==> 객체 ==> 컬렉션 ==> 전체검색으로 활용
// 자동차 색 첫 글자가 p로 시작하는 거 다 나와봐라
for(int i=0; i<alist1.size(); i++) {
if(alist1.get(i).getColor().startsWith("p")) {
System.out.println(alist1.get(i));
}
}
System.out.println();
for(int i=0; i<alist1.size(); i++) {
if(alist1.get(i).getColor().charAt(0) == 'p') {
System.out.println(alist1.get(i));
}
}
System.out.println();
}
}
□ 컬렉션 - 2
package day10.collection;
import java.util.ArrayList;
public class B_collection {
public static void main(String[] args) {
ArrayList arr1 = new ArrayList();
System.out.println(arr1.size()); // 0
// bae[0]=50;
// 입력은 add(), 출력은 get()
// arr1.add(500); // 권장 x
// 사용은 int의 class화 형태인 Integer
// null 사용, 계산은 unboxing 하면 가능
// int aa = 30; Interger bb = aa; // auto boxing
// int cc = bb; .aa. auto unboxing
arr1.add(new Integer(500));
arr1.add(new Double(356.87));
arr1.add(new String("ondal"));
arr1.add(new Character('빛'));
System.out.println(arr1.size());
for (int i=0; i<arr1.size(); i++) {
System.out.println(arr1.get(i));
}
arr1.add("빵");
arr1.add("우유");
arr1.add("김밥");
arr1.add("라면");
System.out.println(arr1.size());
arr1.set(6, "과자"); // 0부터 해서 6번째 김밥을 ==> 과자
arr1.remove(7); // 0부터 해서 7번째 라면을 삭제
for (int i=0; i<arr1.size(); i++) {
System.out.println(arr1.get(i));
}
}
}
'IT&코딩 > 국비지원' 카테고리의 다른 글
SQL - 2 (0) | 2023.04.13 |
---|---|
SQL - 1 (0) | 2023.04.13 |
네트워크 - 2 (네트워크) (0) | 2023.03.23 |
네트워크 - 1 (네트워크 이론 및 스레드) (0) | 2023.03.22 |
Java - 1 (0) | 2023.03.20 |