简体   繁体   English

嵌套类上的接口静态方法

[英]Interface Static Methods on Nested Class

I just learned today just a few minutes ago that I can nest a number of static classes within a containing class which I wasn't aware of. 我刚刚在几分钟前才了解到,我可以在一个我不知道的包含类中嵌套许多静态类。 I got used with creating classes with no nested classes at all in the past. 过去,我习惯于创建完全没有嵌套类的类。

I thought that making use of nested classes will help in readability of codes especially when an object or a class has subclasses or types, just like Payment where you need to consider paymentterms. 我认为利用嵌套类将有助于代码的可读性,尤其是当对象或类具有子类或类型时,就像在“付款”中需要考虑付款条款那样。

I find that understanding nested classes and applying it to my coding is very powerful combined with interfaces. 我发现了解嵌套类并将其应用于我的编码与接口结合起来非常强大。

So I tried to apply it to my current project where I design the classes and methods of Payment. 因此,我尝试将其应用到当前的项目中,在该项目中设计付款的类和方法。

public class Payment {

    public static class terms{

        public static class monthly implements Monthly{

            @Override //error here
            public static void setDownpayment(double aDownPayment) //and error here
            {

            }

        }

        public static class quarterly{
            public static void setDownpayment(){
                //do something
            }
        }

        public static class semestral{
            public static void setDownpayment(){
                //do something
            }
        }
    }
} 

and here's the interface I created 这是我创建的界面

public interface Monthly {
    public void setDownpayment(double aDownPayment);
}

I tried to make the setDownpayment() method to be static so I can refer to it like this: 我试图将setDownpayment()方法设置为static因此可以像这样引用它:

Payment.terms.monthly.setDownpayment(aDecimalValue);

But it doesn't seem to allow static methods. 但这似乎不允许使用静态方法。 because there's an error on the 2 lines I commented with " //error here and //and error here " 因为两行都有错误,所以我用“ //error here//and error here ”注释

How do I fix it? 我如何解决它?

Any other possible solution or alternative ways or design suggestions? 还有其他可能的解决方案或替代方法或设计建议吗?

I'd appreciate any help. 我将不胜感激。

Thanks. 谢谢。

In java, You have to override all methods of an implemented Interface , and as static methods are part of classes not Objects and they are not overridable that's why static methods inside interfaces are not allowed (for before java8 ). 在Java中,您必须重写已实现Interface的所有方法,并且由于static方法是Object而不是Object的类的一部分,并且它们是不可重写的,因此这就是为什么接口内部不允许使用static方法的原因(对于java8之前的版本)。

In Java8, static method in Interface is allowed but they must have body inside the interface and you can't override them inside the implementation classes . 在Java8中, 允许在Interface中使用静态方法,但它们必须在接口内部具有主体,并且您不能在实现类内部覆盖它们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM