본문 바로가기
수업노트

23.3.21

by MIniLabo 2023. 3. 21.

o 추상 클래스 Abstract class

Animal class생성 후 실습--------------------------------------------------

abstract class Animal {//추상클래스(아래의 추상메소드로 인해)

String name;

void view() {} //일반메소드

abstract void disp(); //추상메소드(미완성-바디{}가 없음)

 

}//class end

//추상클래스는 부모역할만 주로 한다

//추상클래스를 상속받은 자식클래스는 반드시 추상메소드를 완성해야 함(override 통해)

class Elephant extends Animal {

@Override

void disp() {//바디 없는 추상메소드에 오버라이딩 통해 기능추가

System.out.println("점보");

}

}//class end

class Tuna extends Animal {

@Override

void disp() {

System.out.println("니모");

}

}//class end

------------------------------------------------

/*

● 추상 클래스

- 미완성 클래스

- 객체를 생성할 수 없음(메모리 할당 불가)

- new연산자 직접 사용 불가

- 추상메소드가 1개라도 있으면 추상클래스(추상메소드가 없으면 추상클래스X)

- 추상메소드와 일반메소드가 같이 선언 가능

 

● 추상메소드

- 미완성 메소드

- 형식) 리턴형 함수명();

- 메소드의 body인 {}가 없음

- 메소드의 기능 없이 선언만 해 놓은 것

 

● 인터페이스(interface) : 추상메소드만 선언 가능

 

*/

/////////////////////////////////////////////////

 

//추상클래스는 new연산자로 직접 객체생성 할 수 없다

//Animal ani = new Animal();

 

//추상클래스 직접 객체생성 안되므로 오버라이딩 통해 완성된 자식클래스로 객체생성

Elephant jumbo = new Elephant();

jumbo.disp();

 

Tuna nimo = new Tuna();

nimo.disp();

 

//다형성

//부모는 추상클래스, 자식은 추상클래스에 대한 오버라이딩 통해 객체생성 가능

//부모클래스에 다형성 통해 자식넣기

//부모님께 집사준 자식

Animal animal = new Elephant();

animal.disp();

 

animal = new Tuna();

animal.disp();

===========================================

abstract class Travel { //추상클래스

void view() {} //일반메소드

abstract String travelWhere(); //추상메소드

}//class end

class TypeA extends Travel {

@Override

String travelWhere() {//부모의 추상메소드 불러와 오버라이딩

return "제주도 올레길";

}

}//class end

class TypeB extends Travel {

@Override

String travelWhere() {

return "여의도 벚꽃 축제";

}

}//class end

class TypeC extends Travel {

@Override

String travelWhere() {

return "지리산 둘레길";

}

}//class end

//이하메인함수

public class Test02_abstract {

public static void main(String[] args) {

//추상클래스와 다형성

Travel tour = new TypeA();

System.out.println(tour.travelWhere());

 

tour = new TypeB();

System.out.println(tour.travelWhere());

 

tour = new TypeC();

System.out.println(tour.travelWhere());

}//main() end

===========================

o 인터페이스

//인터페이스 Creature 생성후 실습

------------------------------------------------

interface Creature {//메뉴판같은것, 실제로 구현하는 것은 자식클래스에서

//void disp() {} 에러, 일반메소드는 사용불가

abstract void kind();//추상메소드만 가능

void breathe();//인터페이스에서는 abstract 생략가능

}//interface end

class Tiger implements Creature{//인터페이스->클래스 상속은 implements로

@Override

public void kind() {

System.out.println("포유류");

}//추상메소드 kind() 오버라이딩

 

@Override

public void breathe() {

System.out.println("허파");

}//추상메소드 breathe() 오버라이딩

}//class end

class Salmon implements Creature{

//컨트롤스페이스 또는 메뉴 source의 override/implements method 이용가능

//특히 메이커측에서 제공한 인터페이스 사용시 메뉴활용하면 상속받은 부모메소드 보여줘서 편함

@Override

public void kind() {

System.out.println("어류");

}//추상메소드 kind() 오버라이딩

 

@Override

public void breathe() {

System.out.println("아가미");

}//추상메소드 breathe() 오버라이딩

}//class end

---------------------------------------------

public static void main(String[] args) {

// 인터페이스 interface

/*

- 추상메소드로만 구성

- 추상클래스보다 더 추상화되어 있음

- 상속 : extends 확장, implements 구현

*/

////////////////////////////////////

 

//에러, 인터페이스는 직접 객체생성 불가능

//Creature creature = new Creature();

 

//인터페이스에서의 다형성

//Creature creature에 null값 넣어놓고 필요에따라 자식넣기

Creature creature = null;

 

creature = new Tiger();

creature.kind(); //포유류

creature.breathe(); //허파

 

creature = new Salmon();

creature.kind(); //어류

creature.breathe(); //아가미

===================================

class Unit {

int currentHP;

int x, y;

}//class end

interface Movable{

void move(int x, int y);

}//interface end

interface Attacable{

void attack(Unit u);

}//interface end

interface Fightable extends Movable, Attacable{

//인터페이스 간의 상속은 다중상속 가능

//인터페이스 간의 상속은 extends로 구현

}//interface end

class Fight extends Unit implements Fightable{

//클래스 간의 상속은 extends로 구현

//클래스 간에는 단일상속만 가능

 

 

//Fight가 상속받은 Fightable이 Movable, Attacable을 상속받은 것이므로

//Movable, Attacable 각각의 추상메소드를 오버라이딩해 완성해야 됨

@Override

public void move(int x, int y) {}

@Override

public void attack(Unit u) {}

 

}//class end

class Tetris extends Unit implements Movable, Attacable{

//클래스는 클래스와 인터페이스를 모두 상속받을 수 있음

//인터페이스는 다중상속(구현)가능

 

//상속받은 인터페이스 Movable, Attacable 각각의 추상메소드 오버라이딩

@Override

public void move(int x, int y) {}

 

@Override

public void attack(Unit u) {}

}//class end

public class Test04_interface {

public static void main(String[] args) {

// 클래스와 인터페이스와 상속

 

}//main() end

================================================

o anonymous

interface IMessage{

public void msgPrint();//추상메소드

}//interface end

class Message implements IMessage{

@Override

public void msgPrint() {

System.out.println("Message class");

}

}//class end

 

public class Test05_anonymous {

public static void main(String[] args) {

//익명 내부 객체 Anonymous class

//인터페이스는 직접 객체생성 불가능

//IMessage msg = new IMEssage(); 에러

 

//1)구현클래스 Message 활용

Message msg = new Message();

msg.msgPrint();

 

//2)다형성 활용

IMessage imess = new Message();

imess.msgPrint();

 

//3)익명내부객체 활용

//인터페이스를 상속하는 클래스(여기서는 Message()가 해당)가 없어 계속 추상클래스로 있을 경우

//필요한 곳에 일시적으로 생성

//이벤트가 발생할 때문 실행

//모바일 응용 앱, 자바스크립트, JQuery등에서 많이 사용

//예) $("button").click(){} <-버튼.클릭 이벤트가 있을때만 함수 만들어 실행

IMessage mess = new IMessage() {//정확히는 얘는 객체가 아님

@Override

public void msgPrint() {

System.out.println("익명 내부 객체");

}

};

 

mess.msgPrint();

 

//위의 익명내부객체 mess가 메모리 할당이 잘 되었는지 확인

//oop0321.Test05_anonymous$1@1c4af82c

System.out.println(mess);

 

}//main() end

===========================================

o inner

//WebProgram 클래스 생성 후 실습

---------------------------------

//웹페이지 작성할 때 사용하는 언어

//.jsp .py .php .asp

class Webprogram {

 

String tilte = "Java Program";

 

class Language{

String basic = "JAVA, HTML, CSS, JavaScript";

void display() {

System.out.println("기초수업 : " + basic);

}//end

}//inner class

class Smart{

String basic = "Objective-C, Java OOP, C#";

void display() {

System.out.println("기초수업 : " + basic);

}//end

}//inner class

 

void print() {

Language lang = new Language();

lang.display();

 

Smart sm = new Smart();

sm.display();

}//print() end

 

}//class end

-------------------------------------------------------

public static void main(String[] args) {

//내부클래스 inner class

//클래스 내부에서 선언된 클래스

///////////////////////

 

Webprogram web = new Webprogram();

web.print();

 

 

//에러, 내부클래스는 외부에서 직접 접근 불가능

//Language lang = new Language();

//Smart sm = new Smart();

 

//내부클래스는 외부에서 단계적으로 접근 가능

Language lang = new Webprogram().new Language();

 

Smart sm = new Webprogram().new Smart();

sm.display();

///////////////////////////////////

 

/*

안드로이드 (구글사에서 만든 모바일 전용 os)

class R{

 

class id{

String btn = "버튼";

}

 

}

접근방식 R.id.btn

*/

 

}//main() end

=============================

o //예외처리 Exception

public static void main(String[] args) {

/*

- 자바 클래스 실행(run)시 발생하는 에러

- try ~ catch

- 원인만 알려줌, 해결책X

- finally

- throws

*/

 

//1)예외처리를 하지 않은 경우

/*

System.out.println(1);

//Eception이 발생하면 프로그램은 정상적으로 종료되지 않음

System.out.println(3/0);//ArithmeticException

System.out.println(5);

System.out.println("END");

*/

/////////////////////////////////////////

 

 

//2) 예외처리를 한 경우

/*

//예외가 발생하더라도 프로그램을 정상적으로 종료시킬 수 있다.

try {

//예외 발생이 예상되는 코드 작성

System.out.println(1);

System.out.println(2/0);

System.out.println(3);

} catch(ArithmeticException e) {

//예외가 발생되었을 때 처리할 코드 작성

System.out.println(e);

}//end

System.out.println("END");

*/

/////////////////////////////

 

//3)

/*

try {

System.out.println(1);

int[] num = new int[3];

num[5] = 7;

System.out.println(9);

} catch (ArrayIndexOutOfBoundsException e) {

e.printStackTrace();

}//end

 

System.out.println("END");

 

->예외메시지 뜨고 다음으로 넘어가 end출력

*/

////////////////////////////////////

 

//4)

/*

try {

System.out.println(1);

int num = Integer.parseInt("korea");

System.out.println(num);

System.out.println(3);

} catch (NumberFormatException e) {

System.out.println(e);

}//end

 

System.out.println("END");

*/

/////////////////////////////////

 

//5)

/*

try {

System.out.println(1);

Integer inte = null;

System.out.println(5/inte);

} catch (NullPointerException e) {

System.out.println(e);

}//end

 

System.out.println("end");

*/

/////////////////////

 

//6) 다중 catch문

//하나의 try문 안에 여러 catch문 올 수 있음

/*

try {

int a = 2 / 0;

int b = Integer.parseInt("korea");

int[] num = new int[3];

num[5] = 7;

} catch (ArithmeticException e) {

System.out.println(e);

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println(e);

} catch (NumberFormatException e) {

System.out.println(e);

} catch (NullPointerException e) {

System.out.println(e);

}//end

 

System.out.println("end");

*/

////////////////////////////////

 

//7) catch문 한번에 해결

/*

try {

int a = 2 / 0;

int b = Integer.parseInt("korea");

int[] num = new int[3];

num[5] = 7;

} catch (Exception e) {//다형성

//Exception 클래스 : 모든 예외 발생의 조상 클래스

System.out.println(e);

}//end

 

System.out.println("end");

*/

//////////////////////////////////

 

 

//8) finally문

//예외가 발생 유무와 관계없이 무조건 실행

try {

System.out.println("open");

System.out.println(1/0);

} catch (Exception e) {

System.out.println(e);

}finally {

System.out.println("close");

 

//finally 안에 try catch 또 올 수 있음

}//end

 

System.out.println("end");

 

}//main() end

=====================================

class Test {

//1)각각의 메서드에 try~catch를 직접 이용한 예외처리

/*

public void view() {

try {

int a = 3/0;

} catch (Exception e) {

System.out.println(e);

}//end

}//view() end

 

public void disp() {

try {

int a = Integer.parseInt("korea");

} catch (Exception e) {

System.out.println(e);

}//end

}//disp() end

*/

 

//2) throws를 이용한 예외처리

public void view() throws Exception {

int a = 3/0;

}//view() end

 

public void disp() throws NullPointerException, NumberFormatException{

int a = Integer.parseInt("korea");

}//disp() end

 

 

//os가 개입해서 문제가 발생하지 않도록 조정하는 기법

public synchronized void login() {}

 

}//class end

//이하 메인

public class Test08_throws {

public static void main(String[] args) {

//throws문

//메소드 호출시 예외처리를 한꺼번에 모아서 처리

try {

Test test = new Test();

//test.view();

test.disp();

}catch (Exception e) {

System.out.println(e);

}//end

 

 

 

}//main() end

'수업노트' 카테고리의 다른 글

23.3.23  (0) 2023.03.27
23.3.22  (0) 2023.03.22
23.3.20  (0) 2023.03.20
23.3.17  (0) 2023.03.17
23.03.16  (0) 2023.03.16