Object Oriented Programming

https://www.careercup.com/page?pid=object-oriented-design-interview-questions&n=4

Interfaces

  • Interface methods are default public, so no need to specify public
  • Constant field declarations are implicitly public static final

Default Interface

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

  • default methods will help us in avoiding utility classes, such as all the Collections class method can be provided in the interfaces itself.

  • help us in removing base implementation classes, we can provide default implementation and the implementation classes can chose which one to override.

public interface Interface2 {
    void method2();
    default void log(String str){
        System.out.println("I2 logging::"+str);
    }
}

We know that Java doesn’t allow us to extend multiple classes because it will result in the “Diamond Problem” where compiler can’t decide which superclass method to use. With the default methods, the diamond problem would arise for interfaces too. Because if a class is implementing bothInterface1andInterface2and doesn’t implement the common default method, compiler can’t decide which one to chose.

Static Interface

Java interface static method is part of interface, we can’t use it for implementation class objects.

Java interface static methods are good for providing utility methods, for example null check, collection sorting etc.

Functional Interface

An interface with exactly one abstract method is known as Functional Interface. A new annotation @FunctionalInterface has been introduced to mark an interface as Functional Interface. @FunctionalInterface annotation is a facility to avoid accidental addition of abstract methods in the functional interfaces. It’s optional but good practice to use it.

// Java program to demonstrate lamda expressions to implement
// a user defined functional interface.

@FunctionalInterface
interface Square
{
    int calculate(int x);
}

class Test
{
    public static void main(String args[])
    {
        int a = 5;

        // lambda expression to define the calculate method
        Square s = (int x)->x*x;

        // parameter passed and return type must be
        // same as defined in the prototype
        int ans = s.calculate(a);
        System.out.println(ans);
    }
}

Marker Interfaces

  • Special kind of interfaces which have no methods or other nested constructs defined.

  • Marker interfaces are not contracts per se but somewhat useful technique to “attach” or “tie” some particular trait to the class.

//For example, with respect to Cloneable, the class is marked as being available for cloning 
//however the way it should or could be done is not a part of the interface.
public interface Cloneable {} 
public interface Serializable {}

results matching ""

    No results matching ""