멤버 변수/한수 혹은 클래스에 사용되며 외부에서의 접근을 제한하는 역할
package pkg; // pkg란 이름의 패키지
public class ModifierTest {
private void messageInside(){
System.out.println("This is private modifier");
}
public void messageOutside(){
System.out.println("This is public modifier");
messageInside();
}
protected void messageProtected(){
System.out.println("This is protected modifier");
}
}
import pkg.ModifierTest;
class Child extends ModifierTest{
void callParentProtected(){ // 앞에 아무것도 선언하지 않았기 때문에 default = private 이다.
System.out.println("call my parent's protected method");
super.messageProtected(); // super : 내가 상속받은 부모 클래스를 가리키는 키워드
}
}
public class Main {
public static void main(String[] args) {
ModifierTest modifierTest = new ModifierTest();
modifierTest.messageOutside();
// modifierTest.messageInside(); // 실행되지 않음
// modifierTest.messageProtected(); // 실행되지 않음
}
}
추상메소드를 선언할 수 있는 클래스
상속받는 자식 클래스 없이 인스턴스를 생성할 수 없다.
추상메소드 : 설계만 되어있고, 구현체가 없는 것(자식클래스에서 구현)
예를들어,
int add(int x, int y){
return x + y;
}
여기서 중괄호 부분을 구현체 라고 한다.
abstract class Bird{
private int x,y,z;
void fly(int x, int y, int z){
printLocation();
System.out.println("이동합니다.");
this.x = x;
this.y = y;
if(flyable(z)){
this.z = z;
}else{
System.out.println("그 높이로는 날 수 없습니다.");
}
printLocation();
}
abstract boolean flyable(int z); // 추상메서드
public void printLocation(){
System.out.println("현재위치 {" + x + "," + y + "," + z + "}");
}
}
class Pigeon extends Bird {
@Override
boolean flyable(int z) {
return z < 10000;
}
}
class Peacock extends Bird{
@Override
boolean flyable(int z) {
return false;
}
}
public class Main {
public static void main(String[] args) {
Bird pigeon = new Pigeon();
Bird peacock = new Peacock();
System.out.println("--- 비둘기--- ");
pigeon.fly(1,1,3);
System.out.println("--- 공장새 ---");
peacock.fly(1,1,3);
System.out.println("--- 비둘기 ---");
pigeon.fly(3,3,30000);
}
}
:
--- 비둘기---
현재위치 {0,0,0}
이동합니다.
현재위치 {1,1,3}
--- 공장새 ---
현재위치 {0,0,0}
이동합니다.
그 높이로는 날 수 없습니다.
현재위치 {1,1,0}
--- 비둘기 ---
현재위치 {1,1,3}
이동합니다.
그 높이로는 날 수 없습니다.
현재위치 {3,3,3}
인터페이스는 객체의 특정 행동의 특징을 정의하는 간단한 문법입니다. 인터페이스는 함수의 특징(method signature)인 접근제어자, 리턴타입, 메소드 이름만을 정의합니다. 함수의 내용은 없습니다. 인터페이스를 구현하는 클래스는 인터페이스에 존재하는 함수의 내용({} 중괄호 안의 내용)을 반드시 구현해야합니다.
interface MyInterFace{ // 인터페이스명
void myMethod(); // 추상메서드명
}
매개변수(parameter)를 받고싶다면
interface MyInterFace{
void myMethod(int x);
}
: body 없이 정의하면 된다.
interface Flyable{
void fly(int x, int y, int z);
}
class Pigeon implements Flyable{
private int x,y,z;
@Override
public void fly(int x, int y, int z) {
printLocation();
System.out.println("날아갑니다.");
this.x = x;
this.y = y;
this.z = z;
printLocation();
}
public void printLocation(){
System.out.println("현재위치 {" + x + "," + y + "," + z + "}");
}
}
public class Main {
public static void main(String[] args) {
Flyable pigeon = new Pigeon();
pigeon.fly(1,2,3);
}
}
:
현재위치 {0,0,0}
날아갑니다.
현재위치 {1,2,3}
자바는 상속을 통해 모든 예외 클래스를 정의할 수 있다.
Error
대부분 프로그램이 종료되어야 하는 심각한 문제
대부분 컴퓨터나 JVM이 시스템적으로 동작할 수 없는 상황
try {
// 예외가 발생할 가능성이 있는 코드를 구현합니다.
} catch (FileNotFoundException e) {
// FileNotFoundException이 발생했을 경우,이를 처리하기 위한 코드를 구현합니다.
} catch (IOException e) {
// FileNotFoundException이 아닌 IOException이 발생했을 경우,이를 처리하기 위한 코드를 구현합니다.
} finally {
// 예외의 발생여부에 관계없이 항상 수행되어야하는 코드를 구현합니다.
}
finally 구문은 필수는 아니다.
예외가 발생하지 않는다면 try -> finally 순으로 실행
예제
public class Main {
public static void main(String[] args) {
int number = 5;
int result;
for(int i = 5; i >= 0; i--){
try{
result = number / i;
System.out.println(result);
}catch(Exception e){
System.out.println("Exception 발생: " + e.getMessage());
}finally{
System.out.println("항상 실행되는 finally 구문");
}
}
}
}
:
1
항상 실행되는 finally 구문
1
항상 실행되는 finally 구문
1
항상 실행되는 finally 구문
2
항상 실행되는 finally 구문
5
항상 실행되는 finally 구문
Exception 발생: / by zero -> catch문의 출력문이 출력됨
항상 실행되는 finally 구문
예제
import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try(FileOutputStream out = new FileOutputStream("test.txt")){
out.write("Hello Sparta".getBytes());
out.flush();
} catch (IOException e) {
System.out.println("IOException 발생: " + e.getMessage());
e.printStackTrace();
}
}
}
:
값은 출력되지 않고 test.txt 파일에 "Hello Sparta"라는 글이 적혀있다.
Java에서의 날짜와 시간
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
System.out.println("now usages");
LocalDate date = LocalDate.now();
LocalTime time = LocalTime.now();
LocalDateTime dateTime = LocalDateTime.now();
System.out.println(date);
System.out.println(time);
System.out.println(dateTime);
System.out.println("of() usage");
LocalDate dateOf = LocalDate.of(2022, 11, 15);
LocalTime timeOf = LocalTime.of(21, 20, 25);
System.out.println(dateOf);
System.out.println(timeOf);
}
}
:
now usages
2022-11-15
21:21:30.809493
2022-11-15T21:21:30.809721
of() usage
2022-11-15
21:20: