sat 1/6/2018 interface 1. 2 extending interfaces · sat 1/6/2018 2 interface 1. what is an...
TRANSCRIPT
Sat 1/6/2018
1
INTERFACE 2
1. What is an interface 2 2. When to use INTERFACE 3 3. What are the 3 different ways you can Extending INTERFACES that contain Default Methods 3 4. Implementing INTERFACES : 4 5. Extending INTERFACES : 4 6. Interface Example 5 7. When an ABSTRACT CLASS Implements an INTERFACE 5 8. Does Java support multiple INHERITANCES? 5 9. Why Java doesn't support multiple INHERITANCE 5 10. Does Java 8 support multiple INHERITANCE use default methods Error! Bookmark not defined. 11. Explain the difference between ITERATOR AND ENUMERATION INTERFACE with example. 6 12. What is marker or tagged interface? 7 13. Nested Interface in Java 7 14. What is Java 8 Default Method in Interface 8 15. What is Java 8 Static Method in Interface 8 16. Can an INTERFACE extend another INTERFACE ? 8 17. What is the INTERFACES egregation principle (ISP) 8 18. What is Programming for INTERFACE not implementation 9 19. What is Comparable INTERFACE ? 9 20. What is Comparator? 9 21. Is there any limitation of using INHERITANCE? 9
Sat 1/6/2018
2
INTERFACE
1. What is an interface
Since multiple INHERITANCE is not allowed in Java, INTERFACE is only way to implement multiple INHERITANCE at Type level.
Good OOP design to "program for INTERFACES than implementation" because when you use INTERFACE to
declare reference variable, method return type or method argument you are flexible enough to accept any future implementation of that INTERFACE
All variables declared inside INTERFACE is implicitly public final variable or constants. which brings a useful case of using INTERFACE for declaring Constants and with an INTERFACE you can access constants without referring
them with their class name.
All methods declared inside Java INTERFACES are implicitly public and abstract,
class implements an INTERFACE , thereby inheriting the ABSTRACT METHODS of the INTERFACE .
cannot be instantiated
does not contain any CONSTRUCTORs.
An INTERFACE cannot contain instance fields. The only fields that can appear in an INTERFACE must be
declared both static and final.
INTERFACE can extend multiple INTERFACES
/* File name : NameOfINTERFACE .java */ import java.lang.*; //Any number of import statements public INTERFACE NameOfINTERFACE // INTERFACE is implicitly abstract. You do not need to use the abstract keyword when declaring an INTERFACE . { //Any number of final, static fields //Any number of ABSTRACT METHOD declarations public void eat(); public void travel();
It’s legal for an INTERFACE to extend multiple INTERFACES . for example following code will run without any
compilation error:
INTERFACES ession extends Serializable, Cloneable{ }
Session INTERFACE is also a Serializable and Cloneable. Not true for Class because one Class can only extend
at most another Class.
One Class can implement multiple INTERFACES . They are required to provide implementation of all methods declared inside INTERFACE or they can declare themselves as ABSTRACT CLASS.
Java standard library has many INTERFACES like
Serializable, Cloneable, Runnable or Callable INTERFACE
Ex
INTERFACES essionIDCreator extends Serializable, Cloneable{ String TYPE = "AUTOMATIC"; int createSessionId(); }
// implementation of INTERFACE class SerialSessionIDCreator implements SessionIDCreator{ private int lastSessionId; public int createSessionId() { return lastSessionId++; }
Sat 1/6/2018
3
2. When to use INTERFACE
INTERFACE is best choice for Type declaration or defining contract between multiple parties. If multiple programmers are working in different module of project, they still use each other’s API by defining INTERFACE
and not waiting for actual implementation to be ready.
flexibility and speed in terms of coding and development.
ensures best practices like "programming for INTERFACES than implementation"
results in more flexible and maintainable code.
Though INTERFACE in Java is not the only one who provides higher-level ABSTRACTION, you can also use ABSTRACT CLASS but choosing between INTERFACE in Java and ABSTRACT CLASS is a skill.
3. What are the 3 different ways you can Extending INTERFACES that contain Default Methods
public INTERFACE TimeClient { void setTime(int hour, int minute, int second); default ZonedDateTime getZonedDateTime(String zoneString) { return ZonedDateTime.of(getLocalDateTime(), getZoneId(zoneString)); } }
1. extend INTERFACE inherit the default method. Suppose that you extend the INTERFACE TimeClient as follows:
public INTERFACE AnotherTimeClient extends TimeClient { }
Any class that implements the INTERFACE AnotherTimeClient will have the implementation specified
by the default method TimeClient.getZonedDateTime.
2. Redeclare the default method, which makes it abstract.
public INTERFACE AbstractZoneTimeClient extends TimeClient { public ZonedDateTime getZonedDateTime(String zoneString); }
Any class that implements the INTERFACE AbstractZoneTimeClient will have to implement the
method getZonedDateTime; this method is an ABSTRACT METHOD like all other nondefault (and
nonstatic) methods in an INTERFACE .
3. Redefine the default method, which overrides it.
public INTERFACE HandleInvalidTimeZoneClient extends TimeClient { default public ZonedDateTime getZonedDateTime(String zoneString) { try { return ZonedDateTime.of(getLocalDateTime(),ZoneId.of(zoneString)); } catch (DateTimeException e) { System.err.println("Invalid zone ID: " + zoneString + "; using the default time zone instead."); return ZonedDateTime.of(getLocalDateTime(),ZoneId.systemDefault()); } } }
Any class that implements the INTERFACE HandleInvalidTimeZoneClient will use the implementation of
getZonedDateTime specified by this INTERFACE instead of the one specified by the INTERFACE
TimeClient.
Sat 1/6/2018
4
4. Implementing INTERFACES :
When a class implements an INTERFACE , you can think of the class as signing a contract, agreeing to perform the specific behaviors of the INTERFACE . If a class does not perform all the behaviors of the INTERFACE , the
class must declare itself as abstract.
A class uses the implements keyword to implement an INTERFACE . The implements keyword appears in the
class declaration following the extends portion of the declaration.
/* File name : MammalInt.java */ public class MammalInt implements Animal{ public void eat(){ System.out.println("Mammal eats"); } public void travel(){ System.out.println("Mammal travels"); } public int noOfLegs(){ return 0; } public static void main(String args[]){ MammalInt m = new MammalInt(); m.eat(); m.travel(); } }
This would produce the following result:
Mammal eats
Mammal travels
5. Extending INTERFACES :
An INTERFACE can extend another INTERFACE , similarly to the way that a class can extend another class. The extends keyword is used to extend an INTERFACE , and the child INTERFACE inherits the methods of the parent INTERFACE .
The following Sports INTERFACE is extended by Hockey and Football INTERFACES .
//Filename: Sports.java
public INTERFACES ports { public void setHomeTeam(String name); public void setVisitingTeam(String name); } //Filename: Football.java
public INTERFACE Football extends Sports { public void homeTeamScored(int points); public void visitingTeamScored(int points); public void endOfQuarter(int quarter); } //Filename: Hockey.java
public INTERFACE Hockey extends Sports { public void homeGoalScored(); public void visitingGoalScored(); public void endOfPeriod(int period); public void overtimePeriod(int ot); }
Sat 1/6/2018
5
6. Interface Example
public INTERFACE Dog { public boolean Barks(); public boolean isGoldenRetriever(); }
Now, if a class were to implement this INTERFACE , this is what it would look like:
public class SomeClass implements Dog { public boolean Barks{ // method definition here } public boolean isGoldenRetriever{ // method definition here } }
7. When an ABSTRACT CLASS Implements an INTERFACE
it was noted that a class that implements an INTERFACE must implement all of the INTERFACE 's methods. It is possible, however, to define a class that does not implement all of the INTERFACE 's methods, provided that the
class is declared to be abstract. For example,
ABSTRACT CLASS X implements Y { // implements all but one method of Y } class XX extends X { // implements the remaining method in Y }
In this case, class X must be abstract because it does not fully implement Y, but class XX does, in fact,
implement Y.
8. Does Java support multiple INHERITANCES?
This is the trickiest question in Java if C++ can support direct multiple INHERITANCES than why not Java is the
argument Interviewer often give. Answer of this question is much more subtle then it looks like, because
Java does support multiple INHERITANCES of Type by allowing an INTERFACE to extend other INTERFACES ,
Java doesn't support is multiple INHERITANCES of implementation.
9. Why Java doesn't support multiple INHERITANCE
First reason is ambiguity around Diamond problem
Second and more convincing reason to me is that multiple INHERITANCES does complicate the design and creates problem during casting, CONSTRUCTOR chaining etc
Moveable INTERFACE is some existing INTERFACE and wants to add a new method moveFast().
- If it adds moveFast() method using old technique, then all classes implemeting Moveable will also be changed.
- So, let’s add moveFast() method as default method.
public INTERFACE Moveable { default void moveFast() { System.out.println("I am moving fast, buddy !!"); }
Sat 1/6/2018
6
}
If all classes implementing Moveable INTERFACE do not need change themselves (until some class specifically
wants to override moveFast() method to add custom logic). All classes can directly call instance.moveFast()
method. http://howtodoinjava.com/object-oriented/multiple-INHERITANCE-in-java/
public class Animal implements Moveable { public static void main(String[] args) { Animal tiger = new Animal(); //Call default method using instance reference tiger.moveFast(); } }
All method declarations in an INTERFACE , including default methods, are implicitly public, so you can omit the
public modifier.
10. Explain the difference between ITERATOR AND ENUMERATION INTERFACE with example.
Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
Iterator actually adds one method that Enumeration doesn’t have: remove ().
Whereas in case of Enumeration:
Sat 1/6/2018
7
11. What is marker or tagged interface?
An interface that have no member is known as marker or tagged interface. For example: Serializable, Cloneable, Remote etc. They are used to provide some essential information to the JVM so that JVM may perform some useful operation.
12. Nested Interface in Java
Note: An interface can have another interface i.e. known as nested interface. We will learn it in detail in the nested classes chapter. For example:
interface printable{ void print(); interface MessagePrintable{ void msg(); } }
Sat 1/6/2018
8
13. What is Java 8 Default Method in Interface
Since Java 8, we can have method body in interface. But we need to make it default method. Let's see an example:
File: TestInterfaceDefault.java interface Drawable{ void draw(); default void msg(){System.out.println("default method");} }
class Rectangle implements Drawable{ public void draw(){System.out.println("drawing rectangle");} }
class TestInterfaceDefault{ public static void main(String args[]){ Drawable d=new Rectangle(); d.draw(); d.msg(); } }
Output:
drawing rectangle
default method
14. What is Java 8 Static Method in Interface
Since Java 8, we can have static method in interface.:
File: TestInterfaceStatic.java interface Drawable{ void draw(); static int cube(int x){return x*x*x;} }
class Rectangle implements Drawable{ public void draw(){System.out.println("drawing rectangle");} }
class TestInterfaceStatic{ public static void main(String args[]){ Drawable d=new Rectangle(); d.draw();
System.out.println(Drawable.cube(3)); } }
Output:
drawing rectangle
27
15. Can an INTERFACE extend another INTERFACE ?
Yes an INTERFACE can inherit another INTERFACE , for that matter an INTERFACE can extend more than one INTERFACE .
16. What is the INTERFACES egregation principle (ISP)
Sat 1/6/2018
9
INTERFACES egregation Principle stats that, a client should not implement an INTERFACE , if it doesn't
use that. This happens mostly when one INTERFACE contains more than one functionality, and client only need one functionality and no other. INTERFACE design is tricky job because once you release your INTERFACE you
cannot change it without breaking all implementation. Another benefit of this design principle in Java is, INTERFACE has disadvantage to implement all method before any class can use it so having single functionality
means less method to implement.
17. What is Programming for INTERFACE not implementation
Always program for INTERFACE and not for implementation this will lead to flexible code which can work with any new implementation of INTERFACE . So use INTERFACE type on variables, return types of method or argument
type of methods in Java. This has been advised by many Java programmer including in Effective Java and headfirst design pattern book.
18. What is Comparable INTERFACE ?
It is used to sort collections and arrays of objects using the collections. Sort() and java.utils. The objects of the class implementing the Comparable INTERFACE can be ordered.
19. What is Comparator?
It’s an INTERFACE . It has 2 important methods. But, the frequently used method is compareTo() . It compares 2
different objects.
20. Is there any limitation of using INHERITANCE?
Yes, since INHERITANCE inherits everything from the super class and INTERFACE , it may make the subclass
too clustering and sometimes error-prone when dynamic overriding or dynamic overloading in some situation.