일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
- chartjs
- json
- jsp
- AWS Route53
- 예매로직
- zombie-hit apartment
- terminationGracePeriodSeconds
- AWS
- post
- node.js
- git
- ajax
- 인생이재밌다
- spring
- mongodb
- topologySpreadConstraints
- Java
- spread operator
- MySQL Error
- html
- 영화예매
- sessionStorage
- Bootstrap
- javascript
- ssh
- Kubernetes
- ES6
- AWS RDS
- mysql
- Get
- Today
- Total
jongviet
Feb 26, 2021 - Java 12일차 본문
#Java
*2월26일
1)Interface
-자바에서는 다중 상속이 없기에, 다중 상속 대신 사용하는 것이 바로 인터페이스.. 인터페이스에 속하는 메소드는 무조건 추상 메소드로 선언해야함… 기능이 없는데 왜 상속?!
-비슷한 기능을 가진 메소드들을 공통으로 정의해주고싶을때는 인터페이스를 사용하면 된다.
-인터페이스란 객체의 사용 방법(이름 규칙, 메소드만 표현 가능)에 대해 정의한 것!! 각각 메뉴들이 인터페이스!
-UI(user interface) / UX(user experience) : 모바일에서 예, 아니오 버튼 위치 등등,, 접근성을 말함
-클래스와 비슷하나 interface라고 선언함. 무조건 추상 메소드로서 내부 메소드에 abstract라고 추가하지 않아도 컴파일러가 자동으로 추가해줌.
-text와 call 모두 send 와 receive라는 추상메소드를 sender라는 추상클래스에서 받아서 씀..
-httP 웹툰, 통신 끊겨도 자료 남아있음.. 단방향?! (callback~?!)
-소켓, 스타크래프트 게임.. 통신끊기면 다 날아감..
-상속과 같이 적고, 인터페이스 여러 개 함께 추가 할수도 있음.
-다형성도 인터페이스에 적용 된다..
-인터페이스끼리도 상속 가능함
*public class Pos Extends blabla implements lendable, object
package main;
public class Main {
public static void main(String[] args) {
FlyingCar fc = new FlyingCar("박동훈", 2, 500);
fc.start();
fc.destination("서울");
fc.pay();
fc.InternetOnOrOff();
fc.status();
System.out.println();
ExpressSubmarine sm = new ExpressSubmarine("김길동", 3, 1000);
sm.start();
sm.destination("독도");
sm.pay();
sm.status();
}
}
package main;
public class Vehicle {
String username;
int user_class; // 1~3등급
int balance;
public Vehicle(String username, int user_class, int balance) {
this.username = username;
this.user_class = user_class;
this.balance = balance;
}
void start() {
System.out.println("목적지로 출발합니다.");
}
void feedback() {
System.out.println("여정은 즐거우셨습니까? 만족도를 입력해주세요.");
}
void status() {
System.out.println(username + "님의 잔액 :" + balance + " / [등급:"
+ user_class + "]");
}
}
package main;
public class ExpressSubmarine extends Vehicle implements PayAndDesti {
int price = 50;
public ExpressSubmarine(String username, int user_class, int balance) {
super(username, user_class, balance);
}
@Override
public String destination(String whereToGo) {
System.out.println(whereToGo + "로 모시겠습니다.");
return whereToGo;
}
@Override
public void pay() {
if (user_class >= 2) {
balance -= (price*0.7);
} else {
balance -= price;
}
}
}
package main;
public class FlyingCar extends Vehicle implements PayAndDesti, InternetService {
int price = 100;
int internetPrice = 20;
public FlyingCar(String username, int user_class, int balance) {
super(username, user_class, balance);
}
@Override
public String destination(String whereToGo) {
System.out.println(whereToGo + "로 모시겠습니다.");
return whereToGo;
}
@Override
public void pay() {
if (user_class >= 2) {
balance -= (price*0.9);
} else {
balance -= price;
}
}
@Override
public void InternetOnOrOff() {
System.out.println("인터넷 서비스를 사용합니다. 요금[20]");
balance = balance - internetPrice;
}
}
package main;
public interface PayAndDesti {
void pay();
String destination(String whereToGo);
}
package main;
public interface InternetService {
void InternetOnOrOff();
}
2)예외처리
-암호 입력 실수 시 다시 치게해야지, 꺼지게하면안됨.. 그래서 예외처리 씀!
-일반적으로 순차적으로 진행되다가 에러가 터지면 프로그램 자체가 꺼짐.
-try { } 안에서 오류가 발생 시, catch로 이동하여 catch 안에 코드 실행!
System.out.println("시작");
try {
String str = "10a";
int num = Integer.parseInt(str);
System.out.println(num);
} catch(NumberFormatException e) { // catch안에 잡을 오류 입력, else if처럼 여러 개 사용가능
System.out.println("넘버 오류!");
}catch(ArrayIndexOutOfBoundsExceiption e) { //위에 numberformat 오류가 먼저 잡히면 arrayindex오류는 안잡힘.. 위에꺼 해결해야 보임 순차적으로
System.out.println("배열 인덱스 오류!");
}catch(Exceiption e) { // Exception e는 모~든 오류를 다 잡아줌, else if 개념이므로 exception e는 최하단에 넣어야함!! Exception e가 맨위에 있으면 나머지에 unreachable!
System.out.println("그 외 오류 다잡음!!");
}
System.out.println("끝");
}
3)재귀호출
-숫자입력안했을때 오류발생해서 자기 자신 다시 호출!
-지뢰찾기가 재귀적 용법 구현에 좋음
public class Main {
public static void main(String[] args) {
Control c = new Control();
c.init();
}
import java.util.Scanner;
public class Control {
Scanner sc = new Scanner(System.in);
public void init() {
a();
}
int a = 10;
public void a() {
System.out.println("숫자만 입력!!!");
String input = sc.nextLine();
try {
int num = Integer.parseInt(input);
show(num);
} catch (Exception e) {
a();
}
}
public void show(int num) {
System.out.println(num * 2);
}
}
5)파일저장/파일읽기/파일존재여부확인
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileTest {
public void createFiles() {
FileOutputStream output = null;
String data = "";
//1.새파일만들기,입력하기
FileWriter fw;
try {
fw = new FileWriter("c:/savingpurpose/test.txt", true); //true면 이어쓰기, false면 다지우고 새로쓰기
data = "hello\r\n"; // \r\n 줄바꿈
fw.write(data);
data = "hola\r\n";
fw.write(data);
data = "xinchao\r\n";
fw.write(data);
fw.close();
System.out.println("정상종료");
} catch (IOException e) {
e.printStackTrace();
}
//2.읽기
try {
BufferedReader br = new BufferedReader(new FileReader("c:/savingpurpose/test.txt"));
while (true) {
String line = br.readLine();
if (line == null)
break;
System.out.println(line);
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//3.파일존재여부확인
File file = new File(""c:/savingpurpose/test.txt");
If (file.exist()) {
파일이 있으면~~
}
6)file importing
-select root directory 압축해제된프로젝트폴더
-select archive file : 압축상태인 프로젝트 압축파일
-이미 workspace안에 존재하면 imporing안됨 주의!!
7)Gregorian Calendar
-시스템 운영체제의 시간 불러옴.
GregorianCalendar cal = new GregorianCalendar();
TimeZone timeZone = TimeZone.getTimeZone("Europe/London");
package main;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
GregorianCalendar cal = new GregorianCalendar();
//getAvailableIDs로 타임존 전체 리스트 확인 가능
String[] arr = TimeZone.getAvailableIDs();
for (int i = 0; i < arr.length; i++) {
if(arr[i].contains("America")) {
System.out.println(arr[i]);
}
}
System.out.println(arr.length);
//글로벌 시간 업데이트 할 때, 주로 씀!! 업데이트!
//1.
TimeZone tz1 = TimeZone.getTimeZone("Asia/Shanghai");
cal.setTimeZone(tz1);
System.out.print("Asia/Shanghai의 현재 시간은? " + cal.get(Calendar.HOUR) + ":");
System.out.println(cal.get(Calendar.MINUTE));
TimeZone tz2 = TimeZone.getTimeZone("America/Mexico_City");
cal.setTimeZone(tz2);
System.out.print("America/Mexico_City의 현재 시간은? " + cal.get(Calendar.HOUR) + ":");
System.out.println(cal.get(Calendar.MINUTE));
TimeZone tz3 = TimeZone.getTimeZone("Europe/Minsk");
cal.setTimeZone(tz3);
System.out.print("Europe/Minsk의 현재 시간은? " + cal.get(Calendar.HOUR) + ":");
System.out.println(cal.get(Calendar.MINUTE));
TimeZone tz4 = TimeZone.getTimeZone("Asia/Qatar");
cal.setTimeZone(tz4);
System.out.print("Asia/Qatar의 현재 시간은? " + cal.get(Calendar.HOUR) + ":");
System.out.println(cal.get(Calendar.MINUTE));
}
}
8)Math class / Wrapper class
-주로 랜덤만 사용
-강사님 왈; 왜 있는지도 모르겠다..?! 예전에 만들어진 기능.. 컴퓨터 메모리 효율적으로 사용하기 위함…. 지금은 의미없음.
Int num = (int) (math.random() * 10) -> 0~9까지 난수를 뽑는 코드
int a = 100;
int b = 200;
int num2 = a > b ? a : b; // true면 전자, false면 후자 출력; true : false
System.out.println(num2);
9)Object class
-최상위 클래스로서 모든 클래스는 object 클래스를 상속받는다. 보통은 생략됨. 이때까지 import없이 사용한 주요 클래스는 모두 object class 상속 받았기 때문(String, Math, Exception, System, equals 등)
-문자열에는 우리가 모르는 어떤 값이 들어 갈 수 있음!
-숫자는 == 으로 비교
-객체(클래스) 비교시 == 말고, equals로 하는게 안전함.. String은 class니깐!
-toString은 객체 자신의 정보를 반환한다.
-뭘로 받아야 할지 애매할때, object class로 받으면 됨!!
public class C {
public void test(Object obj1) {
// object 클래스를 통해 만들어진 obj1이라는 객체 Object 클래스를 parameter로 받기에
// 본 java project내 모든 것 사용 가능
if(obj1 instanceof A) {
((A) obj1).show();
} else {
((B) obj1).info(); //b 클래스로 형변환
}
}
}
public class A {
public void show() {
System.out.println("A");
}
}
public class B {
public void info() {
System.out.println("b");
}
}
public static void main(String[] args) {
A a = new A();
B b = new B();
C c = new C();
c.test(a);
c.test(b);
'Java' 카테고리의 다른 글
Mar 3, 2021 - Java 14일차 (0) | 2021.03.04 |
---|---|
Mar 2, 2021 - Java 13일차 (0) | 2021.03.02 |
Feb 25, 2021 - Java 11일차(블로그 이전 재작성) (1) | 2021.03.01 |
Feb 24, 2021 - Java 10일차(블로그 이전 재작성) (0) | 2021.03.01 |
Feb 23, 2021 - Java 9일차(블로그 이전 재작성) (0) | 2021.03.01 |