programing

익명 클래스에 대한 다중 상속

bestcode 2022. 9. 4. 15:21
반응형

익명 클래스에 대한 다중 상속

어나니머스 클래스는 어떻게 2개 이상의 인터페이스를 구현할 수 있습니까?또는 클래스를 확장하고 인터페이스를 구현하려면 어떻게 해야 할까요?예를 들어, 2개의 인터페이스를 확장하는 어나니머스 클래스의 오브젝트를 만듭니다.

    // Java 10 "var" is used since I don't know how to specify its type
    var lazilyInitializedFileNameSupplier = (new Supplier<String> implements AutoCloseable)() {
        private String generatedFileName;
        @Override
        public String get() { // Generate file only once
            if (generatedFileName == null) {
              generatedFileName = generateFile();
            }
            return generatedFileName;
        }
        @Override
        public void close() throws Exception { // Clean up
            if (generatedFileName != null) {
              // Delete the file if it was generated
              generatedFileName = null;
            }
        }
    };

그런 다음 리소스 테스트 블록에서 다음과 같이 사용할 수 있습니다.AutoCloseablelazily-initialized 유틸리티 클래스:

        try (lazilyInitializedFileNameSupplier) {
            // Some complex logic that might or might not 
            // invoke the code that creates the file
            if (checkIfNeedToProcessFile()) {
                doSomething(lazilyInitializedFileNameSupplier.get());
            }
            if (checkIfStillNeedFile()) {
                doSomethingElse(lazilyInitializedFileNameSupplier.get());
            }
        } 
        // By now we are sure that even if the file was generated, it doesn't exist anymore

내부 클래스를 만들고 싶지 않습니다.이 클래스는 사용하는 메서드 이외에는 사용되지 않을 것이 확실하기 때문입니다(또한 다음과 같은 메서드로 선언된 로컬 변수를 사용할 수도 있습니다).var를 입력합니다).

익명 클래스는 다른 Java 클래스와 마찬가지로 확장 또는 구현해야 합니다.java.lang.Object.

예를 들어 다음과 같습니다.

Runnable r = new Runnable() {
   public void run() { ... }
};

여기서,r를 구현하는 익명 클래스의 객체입니다.Runnable.

어나니머스 클래스는 동일한 구문을 사용하여 다른 클래스를 확장할 수 있습니다.

SomeClass x = new SomeClass() {
   ...
};

복수의 인터페이스를 실장할 수 없습니다.그러기 위해서는 명명된 수업이 필요합니다.그러나 익명 내부 클래스나 명명된 클래스는 둘 이상의 클래스를 확장할 수 없습니다.

어나니머스 클래스는 보통 다음과 같은 인터페이스를 구현합니다.

new Runnable() { // implements Runnable!
   public void run() {}
}

JFrame.addWindowListener( new WindowAdapter() { // extends  class
} );

2개 이상의 인터페이스를 실장할 수 있는지 어떤지를 말하는 것은 불가능하다고 생각합니다.그런 다음 이 둘을 조합한 프라이빗인터페이스를 만들 수 있습니다.당신이 왜 익명의 수업을 받길 원하는지 쉽게 상상할 수 없지만:

 public class MyClass {
   private interface MyInterface extends Runnable, WindowListener { 
   }

   Runnable r = new MyInterface() {
    // your anonymous class which implements 2 interaces
   }

 }

아무도 질문을 이해하지 못했나 봐요.이 남자가 원한 건 이런 거였나 봐요

return new (class implements MyInterface {
    @Override
    public void myInterfaceMethod() { /*do something*/ }
});

이것에 의해, 복수의 인터페이스의 실장등이 가능하게 되기 때문입니다.

return new (class implements MyInterface, AnotherInterface {
    @Override
    public void myInterfaceMethod() { /*do something*/ }

    @Override
    public void anotherInterfaceMethod() { /*do something*/ }
});

정말 좋을 것 같은데 자바에서는 요.

메서드 블록 내에서 로컬클래스를 사용할 수 있습니다.

public AnotherInterface createAnotherInterface() {
    class LocalClass implements MyInterface, AnotherInterface {
        @Override
        public void myInterfaceMethod() { /*do something*/ }

        @Override
        public void anotherInterfaceMethod() { /*do something*/ }
    }
    return new LocalClass();
}

어나니머스 클래스는 항상 슈퍼클래스를 확장하거나 인터페이스를 구현합니다.예를 들어 다음과 같습니다.

button.addActionListener(new ActionListener(){ // ActionListener is an interface
    public void actionPerformed(ActionEvent e){
    }
});

게다가 어나니머스 클래스는 복수의 인터페이스를 실장할 수 없지만, 다른 인터페이스를 확장하는 인터페이스를 작성해, 어나니머스 클래스가 실장하도록 할 수 있습니다.

// The interface
interface Blah {
    void something();
}

...

// Something that expects an object implementing that interface
void chewOnIt(Blah b) {
    b.something();
}

...

// Let's provide an object of an anonymous class
chewOnIt(
    new Blah() {
        @Override
        void something() { System.out.println("Anonymous something!"); }
    }
);

익명 클래스가 개체를 만드는 동안 확장 또는 구현 중입니다. 예:

Interface in = new InterFace()
{

..............

}

여기서 어나니머스 클래스는 인터페이스를 구현하고 있습니다.

Class cl = new Class(){

.................

}

여기서 anonymous 클래스는 추상 클래스를 확장하고 있습니다.

언급URL : https://stackoverflow.com/questions/5848510/multiple-inheritance-for-an-anonymous-class

반응형