Home  >  Article  >  Java  >  Inner class implementation of interfaces and abstract classes in Java

Inner class implementation of interfaces and abstract classes in Java

王林
王林Original
2024-04-30 14:03:02454browse

Java allows inner classes to be defined within interfaces and abstract classes, providing flexibility for code reuse and modularization. Inner classes in interfaces can implement specific functions, while inner classes in abstract classes can define general functions, and subclasses provide concrete implementations.

Java 中接口和抽象类的内部类实现

Inner class implementation of interfaces and abstract classes in Java

Java allows inner classes to be defined in interfaces and abstract classes, which facilitates code reuse and modules provides a flexible approach.

Internal classes in interfaces

// Interface with an inner interface
public interface OuterInterface {
    interface InnerInterface {
        void method();
    }
}

Practical case:

You can use internal classes in interfaces to provide specific functions for different implementations. For example, the following code creates an implementation of OuterInterface whose InnerInterface provides a specific implementation of the method() method:

public class OuterInterfaceImpl implements OuterInterface {

    @Override
    public InnerInterface getInnerInterface() {
        return new InnerInterface() {
            @Override
            public void method() {
                System.out.println("InnerInterface method implementation");
            }
        };
    }
}

in abstract class Internal classes

// Abstract class with an inner abstract class
public abstract class OuterAbstractClass {
    abstract class InnerAbstractClass {
        abstract void method();
    }
}

Practical case:

Internal classes in abstract classes can be used to define common functions while allowing subclasses to provide specific implementations. For example, the following code creates an implementation of OuterAbstractClass whose InnerAbstractClass provides an implementation of the method() method:

public class OuterAbstractClassImpl extends OuterAbstractClass {

    @Override
    public InnerAbstractClass getInnerAbstractClass() {
        return new InnerAbstractClass() {
            @Override
            public void method() {
                System.out.println("InnerAbstractClass method implementation");
            }
        };
    }
}

The above is the detailed content of Inner class implementation of interfaces and abstract classes in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn