java接口 in out,默认和静态方法如何在Java 8接口中工作?

I have been trying to get my head around on how actually do the default and static methods work in java 8?

consider the following interface:

public interface Car {

default void drive() {

System.out.println("Default Driving");

}

static int getWheelCount(){

return wheelCount;

}

int wheelCount = 7;

}

and the following implementation:

public class Benz implements Car { }

Now if I go to my main method and write:

public static void main(String[] args){

Car car = new Benz();

car.drive();

System.out.println(Car.getWheelCount());

System.out.println(Car.wheelCount);

}

I would like to know what is really going on under the hood:

Does the default method get called upon the instance of Car in a way which is similar to how abstract classes work?

What new features/modifications did the language need in order to support default and static methods in interfaces?

I know that by default, all the fields in an interface are by default public static final, is that in any way related to my above questions.

With the introduction of default methods, do we have the need of abstract classes anymore?

P.S.

Please feel free to edit the question to make it more useful for fellow SO users.

解决方案

Yes.

Java interface default methods will help us in extending interfaces without having the fear of breaking implementation classes.

What if those computer-controlled car manufacturers add new

functionality, such as flight, to their cars? These manufacturers

would need to specify new methods to enable other companies (such as

electronic guidance instrument manufacturers) to adapt their software

to flying cars. Where would these car manufacturers declare these new

flight-related methods? If they add them to their original interfaces,

then programmers who have implemented those interfaces would have to

rewrite their implementations. If they add them as static methods,

then programmers would regard them as utility methods, not as

essential, core methods.

AFAIK, static methods aren't needed to override, so being final of static methods is coherent. Overriding depends on having an instance of a class. A static method is not associated with any instance of a class so the concept is not applicable. However, default methods must have overrideable property as I quote above.

Can you have default ctor, private fields, instance members in an interface in Java 8?

I like to use thanks to default methods,

list.sort(ordering);

instead of

Collections.sort(list, ordering);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值