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.
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,
instead of