자바공부하기 101

벌써 자바공부하기 101번째 글이네요..^^

앞으로 계속 자바열공!!

 

추상클래스 VS 인터페이스

 

* 유사점

- 하위클래스에서 모든 추상 메서드를 구현해야함

- Upcasting이 가능함

 

* 차이점

-추상클래스

: 추상메서드 외 일반 멤버변슈와 메서드를 가질 수 있다.

: extends를 사용

: 단일 상속만 가능

: 작업의 레벨 분할을 위해서 사용

 

- Interface

: 추상 메서드와 static final 변수만 사용

: Implements를 사용

: 중복 구현 가능

: 공동작업을 위한 상호간의 인터페이스를 위해 사용

 

 

 

 

 

 

 

JAVA공부하기 100

Marker 인터페이스

 

- 어떤 인터페이스는 아무런 메소드도 선언하지않고 어떤 일반적 특성을 가진 클래스임을 선언하는데 사용

 

- 아무런 필드나 메소드 선언하지 않고있다

 

- 예를 들면 Cloneable, Serializable, EventListener 이 있음

 

- RTTI과 혼합되어 사용할 경우, 어떤 클래스가 특정한 목적으로 사용될 수 있음을 표현하는 효과적인 수단이 된다. (RTTI는 이후에 알아봄)

 

 

 

 

JAVA공부하기 99

인터페이스의 확장

- 인터페이스는 extends를 이용하여 확장된 서브 인터페이스를 만들 수 있다.

- 서브 인터페이스는 슈퍼 인터페이스 보다 더 구체화된 데이터 형을 의미한다.

 

 

 

 

public interface Flyer {

int fast=100;        //상수가 됨

 

boolean isAnimal();

}

 

public class Bird implements Flyer {

public void fly(){

System.out.println("날개를 휘저으며 날아감");

}

}

 

public class Airplane implements Flyer {

pulic void fly(){

System.out.println("엔진과 날개를 이용해서 날아감");

}

public boolean isAnimal(){

return false;

}

}

public class FlyerUtil {

public static void show(Flyer f){

f.fly();

System.out.println(f.isAnimal());

}

}

 

public class FlyerMain{

public static void main(String[] args){

System.out.println(Flyer.fast);        //상수

 

Bird b=new Bird();

FlyerUtil.show(b);

Airplane ap=new Airplane();

ap.fly();

FlyerUtil.show(ap);

Flyer f=new Bird();

f.fly();

System.out.println(f.isAnimal());

FlyerUtil.show(f);

Bird bf=(Bird)f;

FlyerUtil.show(bf);

}

}

JAVA공부하기 98

인터페이스의 구현 예제

 

public interface BodySign {

public static final int STRATGHT = 1;

public static final int CURVE = 2;

public static final int DOWN = 1;

public static final int UP = 2;

public static final int RIGHT = 4;

public void countFinger(int how_ball);

public void directionBall(int how_direct);

}

 

public class Catcher implements BodySign {

public void countFinger(int how_ball) {

fi (how_ball == BodySign.STRATGHT) {

System.out.println("직구를 던집니다");

}

else if (how_ball == BodySign.CURVE) {

System.out.println("변화구를 던집니다");

}

}

public void directionBall(int how_direct) {

if (how_direct == BodySSign.UP) {

System.out.println("상향구를 던집니다.");

}

else if (how_direct == BodySign.DOWN) {

System.out..println("하향구를 던집니다.")

}

else if (how_direct == BodySign.LEFT) {

System.out.println("좌향구를 던집니다.");

}

else if (how_direct == BodySign.RIGHT) {

System.out.println("우향구를 던집니다.");

}

public ststic void main(String[] args) {

Catcher c = new Catcher();

c.directionBall(3);        // 제1구.    좌향구를 던집니다.

c.directionBall(BodySign.LEFT);    // 제 2구.    다시 좌향구

c.countFinger(1);        // 제3구. 직구를 던집니다.

c.countFinger(BodySign.CURVE);    //제 4구.    변화구를 던집니다.

}

}

 

 

 

 

JAVA공부하기 97

 

인터페이스란?

- interface는 인터페이스

- 추상 메서드만을 포함하는 추상클래스의 일종

- 메서드는 묵시적으로 public abstract

- 변수는 public static final만 사용가능

- 구현을 위해 implements를 사용

ex) implements Cloneable, Serializable

- 단일 상속의 한계를 극복

: 자바에서는 다중 상속을 지원하지 않았다.

: 그러나 다중 서브타이핑이 필요한 경우도 있다.

 

인터페이스의 구조

- 모든 메서드는 묵시적으로 public abstract

- 변수는 static final만 사용가능

 

 

- 자체적으로 객체 생성이 불가능

-Implements를 사용하여 하위클래스에서 구현

 

JAVA공부하기 96

추상 메서드를 포함하지 않는 추상클래스

 

- 추상메서드를 포함하지 않는 클래스도 추상클래스가 된다.

: 일반 클래스에 abstract 키워드만 명시해 놓은 것

: 일반 클래스와 동일하지만 abstract 키워드가 붙어있기 때문에 객체를 생성할 수 없음

 

- 이런 클래스는 상속 자체만으로 완전한 클래스가 된다.

: 추상 메서드를 포함하지 않기 때문

 

- 무조건 추상 클래스를 상속받게 만들기 위해서

: 상속을 기본으로 만들기 위한 방법론

 

- 추상클래스는 상속을 목적으로 만들어진 특징을 갖고 있음

 


 

 

JAVA공부하기 95

추상클래스의 사용

 

abstract class ship {

public abstract int move();    // 사람을 몇명 나르는가

public abstract int carry();    // 무기를 몇 정 나르는가

}

 

class Boat extends ship {

public int move() {

return 6;

}        // 사람을 몇명 나르는가

public int carry(){

return 6;

}        // 무기를 몇 정 나르는가

public string name(){

return "쌩쌩 보트 : ";

}

}

 

class Cruise extends ship {

public int move() {

return 300;

}        //사람을 몇명 나르는가

publci int carry(){

return 200;

}        // 무기를 몇 정 나르는가

public String name(){

return "전함 무궁화 : " ;

}

}

 

 

class shiputil {

public static void search(ship s){

System.out.println(s.move());

System.out.println(s.carry());

 

if(s instanceof Boat){

Boat b=(Boat)s;

System.out.println("Boat 이름: "+.name());

}

else if(s instance of Cruise){

Cruise b=(Cruise)s;

System.out.println("Cruis 이름: "+b.name());

}

}

}

public class shipMain{

public static void main(string[] args) {

ship ship1=new Boat();

ship ship2=new Cruise();

System.out.println(ship1.move());

System.out.println(ship1.carry());

System.out.println(shtip2.move());

System.out.println(ship2.carry());

shiputil.search(ship2);

}

}

 

 

 

 

java공부하기94

 

추상클래스의 사용 이유

 

- 클래스의 구조를 디자인하기 위함

: 작업을 수평적으로 분할

: 레벨 단위의 구조로 만듦

 

 

 

 

추상클래스의 사용

 

abstract class Shape

{

public abstract void draw();

public abstract void delete();

public void doAll()

{

draw();

delete();

}

}

class Circle extends Shape{

public void draw() {

System.out.println("원을 그립니다.");

}

public void delete() {

System.out.println("원을 지웁니다");

}

}

 

class Triangle extends Shape {

public void draw() {

System.out.println("삼각형을 하나, 둘, 셋, 그립니다.");

}

public void delete() {

System.out.println("삼각형을 지웁니다");

}

}

 

class Rectangle extends Shape {

public void draw() {

System.out.println("사각형을 원, 투, 쓰리, 포 그립니다.");

}

public vlid delete() {

System.out.println("사각형을 지웁니다");

}

}

//abstract을 테스트하기 위한 클래스

public class FigureTest {

public static void main(String[] args) {

Circle c = new Circle();

Triangle t = new Triangle();

Rectangle r = new Rectangle();

Shape s;

s= c;         // 에러발생 안함. C의 클래스 Circle은 s의 서브타입임

s.draw();    // s은 draw라는 메소드를 가진 타입임

s.doAll();

c.draw();

t.draw();

r.draw();

c.delete();

t.delete();

r.delete();

}

}

 

 


 

+ Recent posts