Monday, March 31, 2014

Is Interface going to replace Abstract Class - Java 8?

In Java 8, interface is altered so that it can have abstract methods and default methods. With this alteration, the methods we used to put in an abstract class can now be moved to the interface. Does this mean that we do not need abstract class anymore?

With interfaces in java 8 can have default and abstract methods, it is likely that we are going to create less abstract classes. However, it is unlikely that abstract class is going to be totally replaced by interface, because in an interface, you cannot put private, protected, non-static, non-final fields and non-static and non-default methods.

For example, you have a Car interface:

      public interface Car {
              public void run();
              public String getCarType();

              default boolean readyToDrive() {
                    return  true;
             }
      }

Surely, you don't want to put the carType field in the interface, which automatically becomes final and static. If you can only implement the run method when you are dealing with a specific type of car, you need an abstract class to implement the getCarType method.

The advantages of using interface over abstract class
An interface can extends one or multiple other interfaces, but cannot extends any class.
A class can implement one or multiple interfaces, but can only extends one class.

The advantages of using abstract class over interface
An abstract class can have protected and private fields and methods.

--------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

No comments:

Post a Comment