JAVA_interface

0ne·2024년 6월 9일

java

목록 보기
5/11

abstract class

규칙

  1. Abstract method가 있으면 무조건 그 class는 abstact class이다.
  2. abstract method는 private이 될 수 없음
  3. abstract class는 인스턴스를 만들 수 없음
  • abstract class의 생성자는 객체를 생성할 수 없다. 대신 상속받은 자식 클래스에서 super로 사용가능하다.
  1. 그럼에도 타입으로서 인정되기에 파라미터로 사용가능.

pure abstract class ≡ 모든 메서드가 abstract method인 클래스

  • 실행 로직을 전혀가지고 있지 않은, 그저 다형성을 위한 부모 타입으로써의 껍데기.

  • JAVA_interface

사용하는 이유

  • 의미없는 기능 just 상속용 base class의 인스턴스가 생성되면?
    - abstract class!로 해결
    - abstact class는 인스턴스를 만들 수 없음
  • 새로운 자식 class를 만들 때 까먹고 override하지 않을 문제
    - abstract method는 직접 정의하도록 자바에서 제약을 줌
    - abstact method는 자식 클래스가 반드시 오버라이딩해서 사용해야 함
    - 그렇지 않으면 자식도 추상 클래스가 되어야 함
  1. 코드를 공유하는 경우; 공통된 메서드, 필드가 많은 경우
  2. protected와 private 접근 제어자는 서브클래스와 클래스 내부에서의 접근을 제어하여, 적절한 캡슐화를 제공함
  3. non-static member 사용

정의

method heading + constant로만 구성

  • method definition ㄴㄴ
  • field ㄴㄴ
  • "abstract" method의 모음; 그렇다고 abstract를 정의에 쓰면 안됨

interface도 type임

parameter로 쓰일 수 있음

constants

public static final (굳이 안적어도 됨)

implements

여러개의 interface를 implement할 수 있음

i) abstract class가 구현하는 경우

모든 method define 할 필요 없음
define하지 않은 method는 abstract로 표시

ii) non-abstract class가 구현하는 경우

모든 method define 필요

주의점

public!!

모든 method가 public으로 declare되어야 함
implement하는 class도 interface에 있는 method를 define할 때 public으로 해야함.

inconsistent interfaces

같은 constant define but value 상이

같은 method signature(header; 메소드 이름, 파라미터 리스트) 다른 return type

class VS interface

공통점

1) (파일명 = Interface명).java 로 쓰임
2) 컴파일시 .class로 byte code가 나타남

차이점

FeatureClassInterface
Instantiationㅇㅇㄴㄴ
ConstructorsContains constructorsDoes not contain constructors
MethodsCan have both abstract and concrete methodsAll methods are abstract
Instance variablesㅇㅇㄴㄴ (only static and final fields)
InheritanceExtended by a classImplemented by a class
Multiple inheritanceCannot extend multiple classesCan extend multiple interfaces

interface의 inheritance

다중 상속 가능

interface A {
    void methodA();
}

interface B {
    void methodB();
}

interface C extends A, B {
    void methodC();
}

상속관계에 있는 interface를 구현한 class

base interface, derived interface의 모든 method를 구현해야 함


Comparable interface

single sorting method에 이용

Arrays.sort()를 사용하려면 Comparable을 implement한 objects만 가능

public int compareTo(Object other)만 구현하면 됨

같은 type일 때, 정의한 기준에 따라 비교 가능

아니라면 ClassCastException throw

return 값

음수this < other
0this = other
양수this < other

java.lang => import 필요 ㄴㄴ

public class Person implements Comparable<Person> {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public int compareTo(Person other) {
        return this.name.compareTo(other.name);
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + "}";
    }

    public static void main(String[] args) {
        Person[] people = {
            new Person("Alice", 30),
            new Person("Bob", 25),
            new Person("Charlie", 35)
        };

        Arrays.sort(people);

        for (Person person : people) {
            System.out.println(person);
        }
    }
}
profile
@Hanyang univ(seoul). CSE

0개의 댓글