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);