티스토리 뷰

JAVA

abstract & Interface in java

seoca 2019. 1. 17. 15:29



abstract 


In Java, abstract class can have without any abstract method. However, if there is an abstract class in a class, the class must be the abstract class. The abstract class is not able to be instantiated but allow to be inherited. Moreover, by creating subclass, reference of derive class can be created. 

You can have a reference to an abstract class by creating some other class that derives from your abstract classabstract class can have final method(s) which is not allowed to be overridden by subclasses.

When inherited class creates instance, a constructor in superclass is called.


1. 추상클래스는 인스턴스 생성이 불가능하다는 것만 제외하면 일반클래스와 동일하다.

2. 상속을 강제한다.

3. abstract method가 있다면 Class역시 abstract class가 되어야 한다.

4. abstract method 는 내용이 없고 상속받은 클래스에서 구현되어져야 한다.

5. 생성자나 메소드 오버라이딩의 원리도 그대로 적용이 된다. 

6. abstract class 를 상속 받은 클래스는 abstract method 를 반드시 오버라이딩해야한다. 




Example code


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
abstract class Parent{ 
    Parent() { System.out.println("Parent Constructor Called"); } 
    //constructor of parent class
    abstract void emp(); 
    void num(){ System.out.println("reference called"); }
class Derived extends Parent { 
    Derived() { System.out.println("Derived Constructor Called"); } 
    //constructor of derived class
    void emp() { System.out.println("Derived emp() called"); } 
public class Main { 
    public static void main(String args[]) {  
       Parent p = new Derived();
        p.num();
    } 
cs



Result


Parent Constructor Called Derived Constructor Called

reference Called








Interface


In Java, since multiple inheritances are not supported, the interface can be an alternative way to achieve multiple inheritances. It gives loose coupling as well, making classes separately. 

Interface is like a blueprint to let other classes specify what to do but how. Interface only has an empty shell and other classes take the body part. Thus, Interface itself cannot do anything.

Variables declared in Interface are implicitly public static final. 

Interface can not create instance but it can make reference of it that refers to object of one of its implementing class


1. interface는 다중 구현이 가능하기에 다중상속을 허용하지 않는 자바에서 대안으로 사용할 수 있다. 

2. abstract과 달리 interface는 청사진과 같은 역할을 하기에 각 클래스들에게 어떤식으로 클래스가 구성되어야 하는지 틀을 제시하는 것으로 해석할 수 있다. 그에 반해 abstract은 interface보다 지켜져할 룰이 더 있기에 조금 더 강하게 클래스들에게 원하는 방식을 명령하는 느낌으로 해석될 수 있다. 

3. abstract은 구체적 로직을 포함하는 메서드가 포함되는 것이 가능하며 extends를 사용하여 '상속'을 강제하는 반면, interface는 구체적이 로직이 포함된 메서드의 포함이 불가능하며 implements 키워드를 사용하여 '구현'을 강제한다.

4. Interface에 선언되는 변수들은 public static final 로 지정된다(다른곳으로 가지고가서 사용할 수 있도록). 즉, Interface는 abstract method와 final 만을 멤버로 가질 수 있다.

5. Interface는 그 자체로 객체를 생성할 수 없는 대신 구현된 클래스(implementing class) 의 instance를 참조할 수 있다. 





Example code


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
public interface Calculatable {
    public void setOprands(int first, int second, int third) ;
    public int sum(); 
    public int avg();
}
 
class Calculator implements Calculatable {
    int first, second, third;
    public void setOprands(int first, int second, int third) {
        this.first = first;
        this.second = second;
        this.third = third;
    }
    public int sum() {
        return this.first + this.second + this.third;
    }
    public int avg() {
        return (this.first + this.second + this.third) / 3;
    }
}
 
public class CalculatorConsumer {
    public static void main(String[] args) {
        Calculator c = new Calculator();
        c.setOprands(102030);
        System.out.println(c.sum()+c.avg());
    }
}
cs







reference 

https://opentutorials.org/course/1223/6062

https://www.geeksforgeeks.org/abstract-classes-in-java/

'JAVA' 카테고리의 다른 글

String class in Java  (0) 2019.01.20
Collection framework - ArrayList  (0) 2019.01.17
toString method  (0) 2019.01.08
wrapper class in java  (0) 2019.01.07
String methods in Java  (0) 2019.01.07