Skip to main content

Posts

Showing posts with the label JAVA INTERFACE

Does an interface extend Object class in java?

This is one of the toughest and trickiest question in java language. You may also know that only classes in java are inherited from java.lang.Object class. Interfaces in java don’t inherit from Object class. They don’t have default parent like classes in java. But, following two cases may surprise you. Case 1 : If an interface does not extend Object class, then why we can call methods of Object class on interface variable like below ? interface A { } class InterfaceTest { public static void main(String[] args) { A a = null; a.equals(null); a.hashCode(); a.toString(); } } Case 2 : If an interface does not extend Object class, then why the methods of Object class are visible in interface.? interface A { @Override public boolean equals(Object obj); @Override public int hashCode(); @Override public String toString(); } Explanation : Here is the answer, for every public method in Object class, there is an implicit abstract and public method declared in every interface which does not have di...

Java : The diamond problem or Diamond Dead problem or deadly diamond of death?

The "diamond problem" (sometimes referred to as the "deadly diamond of death") is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If there is a method in A that B and C have overridden, and D does not override it, then which version of the method does D inherit: that of B, or that of C? For example, in the context of GUI software development, a class Button may inherit from both classes Rectangle (for appearance) and Clickable (for functionality/input handling), and classes Rectangle and Clickable both inherit from the Object class. Now if the equals method is called for a Button object and there is no such method in the Button class but there is an overridden equals method in Rectangle or Clickable (or both), which method should be eventually called? It is called the "diamond problem" because of the shape of the class inheritance diagram in this situation. In this case, class A is at the top, both ...