웹사이트 검색

자바의 인터페이스


Java의 인터페이스는 핵심 개념 중 하나입니다. 자바 인터페이스는 자바 프로그래밍 언어의 핵심 부분으로 JDK뿐만 아니라 자바 디자인 패턴에서도 많이 사용된다. 대부분의 프레임워크는 자바 인터페이스를 많이 사용합니다.

자바의 인터페이스

자바 인터페이스 예제

위의 요구 사항에 따라 Shape 인터페이스는 다음과 같습니다. 모양.자바

package com.journaldev.design;

public interface Shape {

	//implicitly public, static and final
	public String LABLE="Shape";
	
	//interface methods are implicitly abstract and public
	void draw();
	
	double getArea();
}

Java의 인터페이스에 대한 중요 사항

  1. interface is the code that is used to create an interface in java.

  2. We can’t instantiate an interface in java.

  3. Interface provides absolute abstraction, in last post we learned about abstract classes in java to provide abstraction but abstract classes can have method implementations but interface can’t.

  4. Interfaces can’t have constructors because we can’t instantiate them and interfaces can’t have a method with body.

  5. By default any attribute of interface is public, static and final, so we don’t need to provide access modifiers to the attributes but if we do, compiler doesn’t complain about it either.

  6. By default interface methods are implicitly abstract and public, it makes total sense because the method don’t have body and so that subclasses can provide the method implementation.

  7. An interface can’t extend any class but it can extend another interface. public interface Shape extends Cloneable{} is an example of an interface extending another interface. Actually java provides multiple inheritance in interfaces, what is means is that an interface can extend multiple interfaces.

  8. implements keyword is used by classes to implement an interface.

  9. A class implementing an interface must provide implementation for all of its method unless it’s an abstract class. For example, we can implement above interface in abstract class like this: ShapeAbs.java

    package com.journaldev.design;
    
    public abstract class ShapeAbs implements Shape {
    
    	@Override
    	public double getArea() {
    		// TODO Auto-generated method stub
    		return 0;
    	}
    
    }
    
  10. We should always try to write programs in terms of interfaces rather than implementations so that we know beforehand that implementation classes will always provide the implementation and in future if any better implementation arrives, we can switch to that easily.

Java 인터페이스 구현 예

이제 Java에서 Shape 인터페이스의 일부 구현을 살펴보겠습니다. 서클.자바

package com.journaldev.design;

public class Circle implements Shape {

	private double radius;

	public Circle(double r){
		this.radius = r;
	}
	
	@Override
	public void draw() {
		System.out.println("Drawing Circle");
	}
	
	@Override
	public double getArea(){
		return Math.PI*this.radius*this.radius;
	}

	public double getRadius(){
		return this.radius;
	}
}

Circle 클래스는 인터페이스에 정의된 모든 메서드를 구현했으며 getRadius()와 같은 자체 메서드도 일부 포함하고 있습니다. 인터페이스 구현에는 여러 유형의 생성자가 있을 수 있습니다. Shape 인터페이스에 대한 또 다른 인터페이스 구현을 살펴보겠습니다. 직사각형.자바

package com.journaldev.design;

public class Rectangle implements Shape {

	private double width;
	private double height;
	
	public Rectangle(double w, double h){
		this.width=w;
		this.height=h;
	}
	@Override
	public void draw() {
		System.out.println("Drawing Rectangle");
	}

	@Override
	public double getArea() {
		return this.height*this.width;
	}

}

재정의 주석 사용에 주목하고 Java에서 메서드를 재정의할 때 항상 재정의 주석을 사용해야 하는 이유에 대해 알아보세요. 다음은 구현이 아닌 인터페이스 측면에서 코딩하는 방법을 보여주는 테스트 프로그램입니다. ShapeTest.java

package com.journaldev.design;

public class ShapeTest {

	public static void main(String[] args) {
		
		//programming for interfaces not implementation
		Shape shape = new Circle(10);
		
		shape.draw();
		System.out.println("Area="+shape.getArea());
		
		//switching from one implementation to another easily
		shape=new Rectangle(10,10);
		shape.draw();
		System.out.println("Area="+shape.getArea());
		}

}

위의 Java 인터페이스 예제 프로그램의 출력은 다음과 같습니다.

Drawing Circle
Area=314.1592653589793
Drawing Rectangle
Area=100.0

Java 인터페이스 이점

  1. 인터페이스는 모든 구현 클래스에 대한 계약을 제공하므로 구현 클래스는 우리가 사용하는 메서드를 제거할 수 없기 때문에 인터페이스 측면에서 코드에 유용합니다.
  2. 인터페이스는 유형을 정의하고 코드에서 최상위 계층을 생성하기 위한 시작점으로 적합합니다.
  3. 자바 클래스는 여러 인터페이스를 구현할 수 있으므로 대부분의 경우 인터페이스를 상위 클래스로 사용하는 것이 좋습니다.

자바 인터페이스의 단점

인터페이스는 많은 이점을 제공하지만 몇 가지 단점도 있습니다.

  1. We need to chose interface methods very carefully at the time of designing our project because we can’t add of remove any methods from the interface at later point of time, it will lead compilation error for all the implementation classes. Sometimes this leads to have a lot of interfaces extending the base interface in our code that becomes hard to maintain.

  2. If the implementation classes has its own methods, we can’t use them directly in our code because the type of Object is an interface that doesn’t have those methods. For example, in above code we will get compilation error for code shape.getRadius(). To overcome this, we can use typecasting and use the method like this:

    Circle c = (Circle) shape;
    c.getRadius();
    

    Although class typecasting has its own disadvantages.

그게 내가 자바에서 인터페이스에 대해 가진 전부입니다. 우리는 자바 인터페이스를 많이 사용하기 때문에 그 기능을 알고 있어야 합니다. 시스템을 설계하고 클라이언트와 인터페이스를 구현하는 하위 클래스 간의 계약으로 인터페이스를 사용하는지 확인하십시오. 업데이트: Java 8은 기본 메서드 및 정적 메서드 구현을 도입하여 인터페이스 정의를 변경했습니다. 자세한 내용은 Java 8 인터페이스를 참조하십시오.